-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
232 lines (187 loc) · 5.36 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
'use strict';
// Load Environment Variables from the .env file
const dotenv = require('dotenv')
dotenv.config();
// Application Dependencies
const express = require('express');
const cors = require('cors');
const superagent = require('superagent');
const pg = require('pg');
// Database Connection Setup
if (!process.env.DATABASE_URL) {
throw 'Missing DATABASE_URL';
}
const client = new pg.Client(process.env.DATABASE_URL);
client.on('error', err => { throw err; });
// Application Setup
const PORT = process.env.PORT;
const app = express();
app.use(cors()); // Middleware
app.get('/', (request, response) => {
response.send('City Explorer Goes Here');
});
app.get('/bad', (request, response) => {
throw new Error('oops');
});
app.get('/paypal', (request, response) => {
response.send(process.env.PAYPAL_URL);
});
// Add /location route
app.get('/location', locationHandler);
const locationCache = {
// "cedar rapids, ia": { display_name: 'Cedar Rapids', lat: 5, lon: 1 }
};
function getLocationFromCache(city) {
const cacheEntry = locationCache[city];
if (cacheEntry) {
// // Older than 5 seconds? Remove from cache.
// if (cacheEntry.cacheTime < Date.now() - 5000) {
// delete locationCache[city];
// return null;
// }
return cacheEntry.location;
}
return null;
}
function setLocationInCache(city, location) {
locationCache[city] = {
cacheTime: new Date(),
location,
};
console.log('Location cache update', locationCache);
}
// Route Handler
function locationHandler(request, response) {
// const geoData = require('./data/geo.json');
const city = request.query.city;
const locationFromCache = getLocationFromCache(city);
if (locationFromCache) {
response.send(locationFromCache);
return; // or use an else { ... } below
}
const url = 'https://us1.locationiq.com/v1/search.php';
superagent.get(url)
.query({
key: process.env.GEO_KEY,
q: city, // query
format: 'json'
})
.then(locationResponse => {
let geoData = locationResponse.body;
// console.log(geoData);
const location = new Location(city, geoData);
setLocationInCache(city, location);
response.send(location);
})
.catch(err => {
console.log(err);
errorHandler(err, request, response);
});
// response.send('oops');
}
app.get('/weather', weatherHandler);
function weatherHandler(request, response){
const weatherData = require('./data/darksky.json');
// const key = process.env.WEATHER_KEY;
// const lat = request.query.latitude;
// const lon = request.query.longitude;
// superagent.get('whatever weather')
// .query({ key, lat, lon })
// .then(...)
const latitude = request.query.latitude;
const longitude = request.query.longitude;
console.log('/weather', { latitude, longitude });
const weatherResults = [];
weatherData.daily.data.forEach(dailyWeather => {
weatherResults.push(new Weather(dailyWeather));
});
response.send(weatherResults);
}
// Books!
app.get('/books', (request, response) => {
const SQL = 'SELECT * FROM Books';
client.query(SQL)
.then(results => {
console.log(results);
// let rowCount = results.rowCount;
// let rows = results.rows;
let { rowCount, rows } = results;
if (rowCount === 0) {
// TODO: go to the API and get my thing
response.send({
error: true,
message: 'Read more, dummy'
});
} else {
response.send({
error: false,
results: rows,
})
}
})
.catch(err => {
console.log(err);
errorHandler(err, request, response);
});
})
// NORMALLY DO NOT CREATE STUFF IN A GET. PLEASE.
app.get('/books/add', (request, response) => {
let { title, author, genre } = request.query; // destructuring
let SQL = `
INSERT INTO Books (title, author, genre)
VALUES($1, $2, $3)
RETURNING *
`;
let SQLvalues = [title, author, genre];
client.query(SQL, SQLvalues)
.then(results => {
response.send(results);
})
.catch(err => {
console.log(err);
errorHandler(err, request, response);
});
/* NEVER EVER EVER DO THIS
`
INSERT INTO Books (title, author, genre)
VALUES('${title}', '${author}', '${genre}')
`;
// SQL Injection
// title = "', 'whatever', 'whatever'); DELETE FROM Books; --"
*/
})
app.use(notFoundHandler);
// Has to happen after the error might have occurred
app.use(errorHandler); // Error Middleware
// Make sure the server is listening for requests
client.connect()
.then(() => {
console.log('PG connected!');
app.listen(PORT, () => console.log(`App is listening on ${PORT}`));
})
.catch(err => {
throw `PG error!: ${err.message}`
});
// Helper Functions
function errorHandler(error, request, response, next) {
console.log(error);
response.status(500).json({
error: true,
message: error.message,
});
}
function notFoundHandler(request, response) {
response.status(404).json({
notFound: true,
});
}
function Location(city, geoData) {
this.search_query = city; // "cedar rapids"
this.formatted_query = geoData[0].display_name; // "Cedar Rapids, Iowa"
this.latitude = parseFloat(geoData[0].lat);
this.longitude = parseFloat(geoData[0].lon);
}
function Weather(weatherData) {
this.forecast = weatherData.summary;
this.time = new Date(weatherData.time * 1000).toDateString();
}