This repository has been archived by the owner on Oct 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
296 lines (252 loc) · 9.61 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/* eslint-disable consistent-return */
/* eslint-disable camelcase */
/* eslint-disable no-shadow */
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const jwt = require('jsonwebtoken');
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
const environment = process.env.NODE_ENV || 'development';
const configuration = require('./knexfile')[environment];
const database = require('knex')(configuration);
const secretKey = process.env.SECRET_KEY || 'pandapuppies';
app.locals.title = 'Denver History';
app.use(express.static('public'));
app.use((req, res, next) => {
const allowedOrigins = ['http://localhost:3000', 'http://localhost:3001', 'http://historicdenver.surge.sh', 'https://historicdenver.surge.sh'];
const { origin } = req.headers;
if (allowedOrigins.indexOf(origin) > -1) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', true);
return next();
});
// AUTHENTICATION ----------------------
const checkAuth = (request, response, next) => {
const { token } = request.body;
if (!token) {
return response.status(403).send({ error: 'You must be authorized to access this endpoint.' });
}
try {
const decoded = jwt.verify(token, secretKey);
const { email } = decoded;
if (email.toLowerCase().includes('@turing.io')) {
next();
} else {
return response.status(403).send({ error: 'Your email is not authorized' });
}
} catch (error) {
return response.status(403).send({ error: 'Invalid token' });
}
};
app.post('/authenticate', (request, response) => {
const payload = request.body;
const requiredParameters = ['email', 'appName'];
requiredParameters.forEach((param) => {
if (!payload[param]) {
return response.status(422)
.send({ error: `Expected format: {email: <string>, appName: <string> }. You're missing an ${param} property.` });
}
});
const token = jwt.sign(payload, secretKey);
return response.status(201).json({ token });
});
// DISTRICTS ---------------------------
app.get('/api/v1/districts', (request, response) => {
database('districts').select()
.then(districts => response.status(200).json(districts))
.catch(error => response.status(500).json({ error }));
});
app.get('/api/v1/districts/:id', (request, response) => {
database('districts').where('id', request.params.id).select()
.then((district) => {
if (district.length) {
response.status(200).json(district);
} else {
response.status(404).send({ error: 'That district does not exist' });
}
})
.catch(error => response.status(500).json({ error }));
});
app.get('/api/v1/districts/:id/buildings', (request, response) => {
const { id } = request.params;
database('buildings').where('historic_dist', id).select()
.then((buildings) => {
if (buildings.length) {
response.status(200).json(buildings);
} else {
response.status(404).send({ error: 'No buildings found' });
}
})
.catch(error => response.status(500).json({ error }));
});
app.get('/api/v1/districts/:id/buildings/map', (request, response) => {
const { id } = request.params;
database('buildings').where('historic_dist', id).select()
.then((buildings) => {
if (buildings.length) {
const map = buildings.map(({
lat,
lon,
ldmk_name,
aka_name,
year_built,
ldmk_num,
id,
description,
photo_link,
}) => ({
lat,
lon,
ldmk_name,
aka_name,
year_built,
ldmk_num,
id,
description,
photo_link,
}));
response.status(200).json(map);
} else {
response.status(404).send({ error: 'No buildings found' });
}
})
.catch(error => response.status(500).json({ error }));
});
app.post('/api/v1/districts', checkAuth, (request, response) => {
const { name } = request.body;
if (!name) {
return response.status(422).send({ error: 'Please name your district' });
}
database('districts').insert({ name }, 'id')
.then((district) => {
response.status(201).json(`You created a district, ${name} with an ID of ${district[0]}`);
})
.catch(error => response.status(500).send({ error }));
});
app.delete('/api/v1/districts', checkAuth, (request, response) => {
const { id } = request.body;
if (!id) {
return response.status(422).send({ error: 'Please include the id of the district to delete' });
}
database('districts').where('id', id).del()
.then((districtId) => {
if (districtId) {
response.status(202).json(`You deleted district ${id}`);
} else {
response.status(404).send({ error: `Could not find district with id ${id}` });
}
})
.catch((error) => {
response.status(500).send({ error: error.message });
});
});
// SEARCH ------------------------------------------
app.get('/api/v1/search', (request, response) => {
const key = Object.keys(request.query)[0];
const value = Object.values(request.query)[0];
database('buildings').where(key, value).select()
.then((result) => {
if (result.length) {
response.status(200).json(result);
} else {
response.status(404).json({ error: `Property '${key}' with value '${value}' not found.` });
}
})
.catch(error => response.status(500)
.send({ 'Database error': `Search parameters must be correctly defined. SQL says: ${error.message}. Please see documentation.` }));
});
// BUILDINGS ---------------------------------------
app.get('/api/v1/buildings', (request, response) => {
database('buildings').select()
.then(buildings => response.status(200).json(buildings))
.catch(error => response.status(500).json({ error }));
});
app.get('/api/v1/buildings/:id', (request, response) => {
const { id } = request.params;
database('buildings').where('id', id).select()
.then((result) => {
if (result.length) {
response.status(200).json(result);
} else {
response.status(404).send({ error: 'That building does not exist' });
}
})
.catch(error => response.status(500).json({ error }));
});
app.patch('/api/v1/buildings/:id/description', checkAuth, (request, response) => {
const { id } = request.params;
const { description } = request.body;
if (!description || !description.length) {
return response.status(422).send({ error: 'Description is required' });
}
database('buildings').where('id', id).select()
.then((result) => {
if (result.length) {
database('buildings').where('id', id).update({ description })
.then(() => response.status(200).json('description changed successfully'));
} else {
return response.status(404).send({ error: 'That building does not exist' });
}
})
.catch(error => response.status(500).json({ error }));
});
app.patch('/api/v1/buildings/:id/aka_name', checkAuth, (request, response) => {
const { id } = request.params;
const { akaName } = request.body;
if (!akaName || !akaName.length) {
return response.status(422).send({ error: 'aka_name is required' });
}
database('buildings').where('id', id).select()
.then((result) => {
if (result.length) {
database('buildings').where('id', id).update({ aka_name: akaName })
.then(() => response.status(200).json(`aka_name changed successfully on ${id}`));
} else {
return response.status(404).send({ error: 'That building does not exist' });
}
})
.catch(error => response.status(500).json({ error }));
});
app.post('/api/v1/buildings', checkAuth, (request, response) => {
const payload = request.body;
delete payload.token;
const desiredParams = ['ldmk_num', 'ldmk_name', 'aka_name', 'ord_num', 'ord_year', 'address_line1', 'address_line2', 'situs_num', 'situs_dir', 'situs_st', 'situs_type', 'state_hist_num', 'year_built', 'arch_bldr', 'document', 'photo_link', 'notes', 'gis_notes', 'description', 'address_id', 'historic_dist'];
Object.keys(payload).forEach((key) => {
if (!desiredParams.includes(key)) {
return response.status(422)
.send({
error: `Expected keys are: 'ldmk_num', 'ldmk_name', 'aka_name', 'ord_num', 'ord_year', 'address_line1', 'address_line2', 'situs_num', 'situs_dir', 'situs_st', 'situs_type', 'state_hist_num', 'year_built', 'arch_bldr', 'document', 'photo_link', 'notes', 'gis_notes', 'description', 'address_id', 'historic_dist'. You entered a ${key} property.`,
});
}
});
database('buildings').insert(payload, 'id')
.then(building => response.status(201)
.json(`You made a building with an id of ${building[0]}`))
.catch(error => response.status(500).send({ error }));
});
app.delete('/api/v1/buildings/', checkAuth, (request, response) => {
const { id } = request.body;
if (!id) {
return response.status(422).send({
error: 'Please include the id of the building to delete',
});
}
return database('buildings').where('id', id).del()
.then((buildingId) => {
if (buildingId) {
response.status(202).json(`You deleted building ${id}`);
} else {
response.status(404).send({ error: `Could not find building with id ${id}` });
}
})
.catch(error => response.status(500).send({ error }));
});
app.listen(app.get('port'), () => {
// eslint-disable-next-line no-console
console.log(`${app.locals.title} is running on ${app.get('port')}.`);
});
module.exports = app;