/
server.js
71 lines (61 loc) · 1.73 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
//TODO: WRITE READ ME
//TODO: add to Nommad App readme
// dependencies
const express = require('express');
const bodyParser = require('body-parser');
const yelp = require('yelp-fusion');
require('dotenv').config();
// setup
const app = express();
app.use(bodyParser.json());
// allows response to be shared
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
//// process.env.PORT allows heroku to set port #
var PORT = process.env.PORT || 8080;
// routes
// home page
app.get('/', function(req, res){
res.send('howdy');
})
//TODO: understand what this does and comment it
var handleClientAction = (res, promise) => {
promise.then(response => {
res.json(response.jsonBody);
}).catch(e => {
res.json(e);
});
}
// get access token
// tokens can be revoked so it's best to plug in ID and secret in case
// that occurs to keep app running
const yelpClientPromise = yelp.accessToken(process.env.YELP_CLIENT_ID, process.env.YELP_CLIENT_SECRET)
.then(res => {
console.log('token acquired');
return yelp.client(res.jsonBody.access_token);
}).catch(e => {
console.log(e);
res.status(500).send('error retrieving token');
});
// JSON response route
// call yelp API using token and return JSON
// TODO: find and plug in what information is needed for Nommad App
// TODO: take req params to render data
app.get('/api/:zip', (req, res) => {
yelpClientPromise.then(client => {
handleClientAction(res, client.search({
term:'foodtrucks',
location: req.params.zip,
radius: 1000
}));
}).catch(err => {
console.log(err);
res.status(500).send('error retrieving data from Yelp');
});
});
//start
app.listen(PORT, function(){
console.log(`server listening on ${PORT}`);
});