-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
95 lines (72 loc) · 2.04 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URL);
const Sandwich = require('./models/sandwich');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('Connected to Mongo');
});
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(cors());
app.use(express.json());
app.get('/', (request, response) => {
response.send('SERVER HOME PAGE');
});
app.get('/getSandwiches', async (req, res) => {
const sandos = await Sandwich.find();
res.send(sandos);
});
app.get('/yelpData', getYelp);
async function getYelp(req, res) {
try {
const locations = await axios.get(`https://api.yelp.com/v3/businesses/search`, {
headers: {
authorization: `Bearer ${process.env.YELP_API_KEY}`
},
params: {
categories: 'sandwiches',
location: req.query.location,
term: req.query.term
}
});
const yelpData = locations.data.businesses;
const yelpObjs = yelpData.map(location => {
return new Location(location);
});
res.send(yelpObjs);
}
catch (err) {
handleError(err, res);
}
}
class Location {
constructor(yelpLocationObj) {
this.restaurant = yelpLocationObj.name;
this.lat = yelpLocationObj.coordinates.latitude;
this.lon = yelpLocationObj.coordinates.longitude;
this.yelpUrl = yelpLocationObj.url;
this.addressLines = yelpLocationObj.location.display_address;
console.log(yelpLocationObj);
}
}
app.post('/sandwiches', postSandwiches);
async function postSandwiches(req, res) {
try {
const newSandwich = await Sandwich.create(req.body);
res.send(newSandwich);
}
catch (err) {
handleError(err, res);
}
}
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`listening on http://localhost:${PORT}`));
function handleError(err, res) {
console.log(err);
res.status(500).send('Error!');
}