Jump to content

DATABASE ARE NOT RUNING


jkjk

Recommended Posts

//=============================================================
'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(sqlvalues)
    .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(citydata.body));
      }
    });
}
 
function dataStoreLocation(citydata) {
  const location = new Location(citydata[0]);
  let SQL = `INSERT INTO locations (formatted_query, latitude, longitude) 
VALUES ($1, $2, $3) 
RETURNING *
`;
let values = [citylocation.latitudelocation.longitude];
  return client.query(SQLvalues)
    .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}`)); })
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...