//=============================================================
'use strict';
require('dotenv').config();
const express = require('express');
const superagent = require('superagent');
const cors = require('cors');
const pg = require('pg');
const client = new pg.Client();
const PORT = process.env.PORT || 3000;
const server = express();
server.use(cors());
//=====================================================
//====================================================
server.listen(PORT,()=>{
console.log(`Listening on PORT ${PORT}`)
})
server.get('/', (req,res)=>{
res.status(200).send('it is working');
})
//====================================================
// creating the route
server.get('/location', locationHandler)
// creating the constructor
function Location (city,locationData){
this.search_query = city;
this.formatted_query = locationData[0].display_name;
this.latitude = locationData[0].lat;
this.longitude = locationData[0].lon;
}
// creating the handler function
function locationHandler(req,res){
let city = req.query['city'];
getLocation(city)
.then(data =>{
res.status(200).send(data)
})
}
// creating the getLocation function
function getLocation(city) {
let sql = `SELECT * FROM location WHERE formatted_query = $1`;
let values = [city];
return client.query(sql, values)
.then(results => {
if (results.rowCount) {
return results.rows[0];
} else {// in case we don't have the data locally , we get it from the API
const url = `https://us1.locationiq.com/v1/search.php?key=${GEOCODE_API_KEY}&q=${city}&format=json&limit=1`;
return superagent.get(url)
.then(data => dataStoreLocation(city, data.body));
}
});
}
function dataStoreLocation(city, data) {
const location = new Location(city, data[0]);
let SQL = `INSERT INTO locations (formatted_query, latitude, longitude)
VALUES ($1, $2, $3)
RETURNING *
`;
let values = [city, location.latitude, location.longitude];
return client.query(SQL, values)
.then(results => results.rows[0]);
}
===============================================
server.use('*',(req,res)=>{
res.status(404).send('page was not found');
});
server.use((error,res,req)=>{
res.status(500).send(error);
});
client.on('error', error => { throw error; })
client.connect().then(() => { server.listen(PORT, () => console.log(`Server runs on ${PORT}`)); })