-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
465 lines (403 loc) · 10.7 KB
/
app.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
const sqlite3 = require('sqlite3').verbose();
const axios = require('axios');
let compression = require("compression");
let express = require("express");
let app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded());
var exphbs = require('express-handlebars');
const { check, validationResult } = require('express-validator/check');
const { sanitizeBody } = require('express-validator/filter');
var fs = require('fs');
var key = fs.readFileSync('encryption/private.key');
var cert = fs.readFileSync( 'encryption/certificate.crt' );
var https = require('https');
require('dotenv').load();
app.engine('handlebars', exphbs({
defaultLayout: 'main',
helpers:{
commaSeparated:function(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
}
}));
app.set('view engine', 'handlebars');
app.get('/', function (req, res) {
let summaryFile = fs.readFileSync("public/js/summary.json");
let summaryData = JSON.parse(summaryFile);
let tocFile = fs.readFileSync("public/js/toc-units.json");
let tocData = JSON.parse(tocFile);
res.render('home', {
layout: false,
summaryData:summaryData,
tocData:tocData
});
});
app.get("/articles/activity", function(req, res){
res.render('articles/activity-overview', {layout:false})
})
app.get("/articles/TOC", function(req, res){
res.render("articles/TOC", {layout:false})
})
app.use(compression());
app.use(express.static("public"));
// axios.interceptors.request.use(request => {
// console.log('Starting Request', request)
// return request
// });
const validZips = [
90042,
90028,
90062,
91601,
90044,
91316,
90036,
90011,
90048,
91605,
91602,
90045,
90037,
91401,
91607,
90066,
90230,
91406,
91325,
91436,
90025,
90049,
90065,
90291,
91403,
90002,
90038,
91326,
91345,
90003,
90068,
91324,
90272,
91307,
90069,
91402,
91311,
91606,
91356,
90034,
91604,
90026,
90061,
91306,
90043,
91304,
90041,
90077,
91352,
91331,
91367,
90004,
91423,
90024,
90035,
91342,
91411,
91344,
90064,
90094,
90744,
91343,
91405,
91040,
90063,
90032,
90006,
90020,
91335,
91042,
90501,
90019,
90046,
90029,
90031,
90059,
90731,
90210,
90067,
90023,
90039,
90016,
90001,
91364,
91303,
90007,
90047,
90293,
90732,
90027,
90015,
90710,
90018,
90012,
90033,
90005,
91504,
90402,
90017,
91205,
90008,
90248,
90292,
90014,
90247,
91105,
91340,
90057,
91214,
90013,
90717,
90010,
90232,
90212,
91505
];
// For info page
app.get("/info/:zip", function(req, res){
res.redirect(`../info.html?zip=${req.params.zip}`);
});
app.post("/info/search", [check('zip').isLength(5).isIn(validZips).trim().withMessage("That ZIP code isn’t listed in the city of Los Angeles.")], function(request, response){
const errors = validationResult(request);
if (!errors.isEmpty()) {
console.log(errors);
return response.end();
}
return response.redirect(`../info.html?zip=${request.body.zip}`);
});
// Returns array of ZIP objects containing neighborhood descriptions
app.get('/api/neighborhoods', function(request, response){
let db = new sqlite3.Database('permit_data.db', sqlite3.OPEN_READONLY, (err) => {
if (err) {
return console.error(err.message);
}
});
let sql = `SELECT * FROM attributes LEFT JOIN costs ON attributes.ZIP = costs.ZIP ORDER BY attributes.ZIP`;
db.all(sql,[],(err, rows ) => {
if (err) {
throw err;
}
zipHolder = [];
rows.forEach((row) => {
zipHolder.push({
"zipCode":row.ZIP,
"description":row.Description,
"units":{
"unitsAll":row.UnitsAll,
"units2019":row.Units2019,
"units2018":row.Units2018,
"units2017":row.Units2017,
"units2016":row.Units2016,
"units2015":row.Units2015,
"units2014":row.Units2014,
"units2013":row.Units2013
},
"costs":{
"medianIncome":row.MedIncome,
"medianHousingCost":row.MedHousingCost,
"percentage":row.Percentage
}
});
});
response.json(zipHolder);
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
});
});
// Returns array of information about a ZIP using the param in the request
app.get('/api/neighborhoods/:zip', function(request, response){
let db = new sqlite3.Database('permit_data.db', sqlite3.OPEN_READONLY, (err) => {
if (err) {
return console.error(err.message);
}
});
let sql = `SELECT * FROM attributes, demographics, costs WHERE attributes.ZIP = ${request.params.zip} AND demographics.ZIP = ${request.params.zip} AND costs.ZIP = ${request.params.zip}`;
db.get(sql,[],(err, row) => {
if (err) {
throw err;
}
zipHolder = [];
zipHolder.push({
"zip-code":row.ZIP,
"description":row.Description,
"units":{
"unitsAll":row.UnitsAll,
"units2019":row.Units2019,
"units2018":row.Units2018,
"units2017":row.Units2017,
"units2016":row.Units2016,
"units2015":row.Units2015,
"units2014":row.Units2014,
"units2013":row.Units2013
},
"demographics":{
"population":row.Population,
"white":row.White,
"whiteNonHispanic":row.White_Non_Hispanic,
"black":row.Black,
"nativeAmerican":row.Native_American,
"asian":row.Asian,
"hawaiianPacific":row.Hawaiian_Pacific,
"other":row.Other,
"twoOrMore":row.Two_Or_More,
"twoOrMoreOther":row.Two_Or_More_Other,
"twoOrMoreNotOther":row.Two_Or_More_Not_Other,
"percentWhite":row.Percent_White_Non_Hispanic,
"percentMinority":row.Percent_Minority
},
"costs":{
"medianIncome":row.MedIncome,
"medianHousingCost":row.MedHousingCost,
"percentage":row.Percentage
}
});
response.json(zipHolder);
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
});
});
// Use for maps
// Need to add the same 50 at a time logic as the projects list
app.get("/api/neighborhoods/:zip/geojson", function(request, response){
let zipGeo = fs.readFileSync(`geojson/${request.params.zip}.geojson`);
return response.json(JSON.parse(zipGeo));
})
app.get("/api/cityGeoJSON", function(request, response){
var zipCodeInfo;
axios.get("/api/neighborhoods").then(function(results){
zipCodeInfo = results.data;
countyGeo = fs.readFileSync(`geojson/LA_County.geojson`);
countyGeo = JSON.parse(countyGeo);
for (var i=countyGeo.features.length - 1; i >= 0; i--){
var currentZip = parseInt(countyGeo.features[i].properties.zipcode);
if(validZips.includes(currentZip)){
let zipInfo = results.data.find(o => o.zipCode === currentZip);
countyGeo.features[i].properties.description = zipInfo.description;
countyGeo.features[i].properties.units = zipInfo.units;
countyGeo.features[i].properties.costs = zipInfo.costs;
} else {
countyGeo.features.splice(i, 1)
}
}
return response.json(countyGeo);
})
});
// Return shape of the city limits as a polygon
app.get("/api/cityShape", function(request, response){
cityGeo = fs.readFileSync("geojson/LA_City_simplified.geojson");
cityGeo = JSON.parse(cityGeo);
return response.json(cityGeo);
});
// Return ZIP code boundary for one ZIP code
app.get("/api/cityGeoJSON/:zip", function(request, response){
var zipCodeInfo;
countyGeo = fs.readFileSync(`geojson/LA_County.geojson`);
countyGeo = JSON.parse(countyGeo);
singleZIPBound = countyGeo.features.find(zip => zip.properties.zipcode == request.params.zip);
return response.json(singleZIPBound);
});
// Return Metro stations GeoJSON
app.get("/api/metroJSON", function(request, response){
metroGeo = fs.readFileSync("geojson/Metro_Rail_cleaned.geojson")
metroGeo = JSON.parse(metroGeo);
return response.json(metroGeo);
})
// Return all projects for one ZIP code
// Here you set it to return 50 at a time. The offset parameter will tell the Socrata API which 50 to pull. In your page, use ?page=NUMBER to return the proper page, or leave it blank to get the most recent 50
app.get('/api/projects/:zip', function(req, res){
let db = new sqlite3.Database('permit_data.db', sqlite3.OPEN_READONLY, (err) => {
if (err) {
return console.error(err.message);
}
});
let sql = `SELECT * FROM projects WHERE ZIP = ${req.params.zip} ORDER BY Date DESC`;
db.all(sql,[],(err, rows) => {
if (err) {
throw err;
}
projectsHolder = [];
rows.forEach((row) => {
projectsHolder.push({
"zip-code":row.ZIP,
"date":row.Date,
"type":row.Type,
"address":row.Address,
"units":row.Units,
"stories":row.Stories,
"description":row.Description
});
});
res.json(projectsHolder);
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
});
});
app.post('/email/subscribe', [
check('email').isEmail().normalizeEmail().withMessage("That’s not a valid email address."),
check('zip').isLength(5).isIn(validZips).trim().withMessage("That ZIP code isn’t listed in the city of Los Angeles.")
], function(request, response){
const errors = validationResult(request);
if (!errors.isEmpty()) {
// return response.status(422).json({ errors: errors.array() });
return response.status(422).render('home', {
layout: false,
errors: errors.array()
});
}
console.log(request.body.email);
console.log(request.body.zip);
let db = new sqlite3.Database('email.db', (err) => {
if (err) {
return console.error(err.message);
} else {
console.log("Connected to database successfully.")
}
});
// Add to both email address table and table of emails and ZIP codes
db.serialize(() => {
db.run(`INSERT OR IGNORE INTO emails(Email_Address) VALUES('${request.body.email}')`, [], function(error){
if(error){
return console.log(error.message);
} else {
console.log("emails table worked")
}
});
db.run(`INSERT OR REPLACE INTO email_zip_match(email, ZIP) VALUES('${request.body.email}', ${request.body.zip})`, [], function(error){
if(error){
return console.log(error.message);
} else {
console.log("email_zip_match table worked")
}
});
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
});
response.redirect("../subscribe-success.html");
});
https.createServer({key: key, cert: cert}, app).listen(443);
var http = require('http');
http.createServer(app).listen(80);