forked from code-for-dc-edu/school-chooser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
239 lines (213 loc) · 7.29 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
// Module dependencies.
var application_root = __dirname,
express = require('express'),
fs = require('fs'),
request = require('request'),
hashids = require("hashids"),
mongoose = require( 'mongoose' ),
env = require('node-env-file');
// Load environment file if present
if (fs.existsSync('.env')) { env('.env'); }
// Create server
var app = express();
// Create hasher object
var hasher = new hashids("codefordc");
// Configure server
app.configure(function () {
//parses request body and populates request.body
app.use(express.json());
app.use(express.urlencoded());
//checks request.body for HTTP method overrides
app.use(express.methodOverride());
//perform route lookup based on url and HTTP method
app.use(app.router);
//Where to serve static content
app.use(express.static(application_root + '/site'));
//Show all errors in development
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
// MongoDB
var mongoURL = process.env.MONGOHQ_URL || 'mongodb://localhost/school-chooser';
mongoose.connect(mongoURL, function (err, res) {
if (!err) {
console.log('Database connection established.');
} else {
console.log('ERROR: Problem connecting to database at ' + mongoURL + '. ' + err);
}
});
// Schools
// var SchoolSchema = new mongoose.Schema({
// code: Number,
// name: String,
// grades: { type: [String], index: true },
// collegeEnrollment: {
// val: Number,
// sd: Number
// },
// commute: [
// {
// nc: Number,
// val: Number,
// sd: Number
// }
// ],
// culture: {
// val: {
// attendance: Number,
// suspensions: Number,
// withdrawals: Number
// },
// sd: Number
// },
// diversity: {
// val: {
// a: { type: Number, default: 0 }, // Asian
// aa: { type: Number, default: 0 }, // African American
// ai: { type: Number, default: 0 }, // American Indian / Alaskan Native
// h: { type: Number, default: 0 }, // Hispanic
// mr: { type: Number, default: 0 }, // Two or more races
// pi: { type: Number, default: 0 }, // Native Hawaiian / Pacific Islander
// w: { type: Number, default: 0 } // White, non-Hispanic
// },
// sd: Number
// },
// graduationRate: {
// val: Number,
// sd: Number
// },
// growth: {
// val: Number,
// sd: Number
// },
// instructorRatio: {
// val: Number,
// sd: Number
// }
// });
// var School = mongoose.model('School', SchoolSchema);
// Sessions
var SessionSchema = new mongoose.Schema({
grade: String,
address: String,
addressGISValid: Boolean,
xcoord: Number,
ycoord: Number,
neighborhoodCluster: Number,
zonedSchools: [Number],
rankings: {
academicGrowth: Number,
collegeEnrollment: Number,
graduationRate: Number,
instructionalStaffPerStudent: Number,
racialDiversity: Number,
schoolCulture: Number,
studentsFromMyNeighborhood: Number
}
},
{
toJSON: {
transform: function (doc, ret, options) {
ret.hashid = hasher.encryptHex(doc.id);
delete ret._id;
}
}
});
SessionSchema.statics.findByHashid = function (hashid, cb) {
var id = hasher.decryptHex(hashid);
return this.findById(id, cb);
};
SessionSchema.pre('save', true, function (next, done) {
if (this.zonedSchools.length === 0 && this.addressGISValid) {
var session = this,
grade = parseInt(this.grade, 10),
server = (grade >= 9) ? 4 : (grade >= 6) ? 3 : 2,
url = 'http://maps2.dcgis.dc.gov/dcgis/rest/services/DCGIS_APPS/EBIS/MapServer/'
+ server
+ '/query?f=json&returnGeometry=false&geometry=%7B%22x%22%3A%22'
+ this.xcoord
+ '%22%2C%22y%22%3A%22'
+ this.ycoord
+ '%22%7D&geometryType=esriGeometryPoint&outFields=GIS_ID';
request(url, function (err, res, body) {
if (!err && res.statusCode === 200) {
var redirectUrl,
json = JSON.parse(body),
gisId = json.features[0].attributes["GIS_ID"],
match = gisId.match(/dcps_(.*)/);
if (match) {
session.zonedSchools.push(parseInt(match[1]));
done();
} else {
redirectUrl = "http://maps2.dcgis.dc.gov/dcgis/rest/services/DCGIS_APPS/EBIS/MapServer/5/query?f=json&where=CLOSED_GIS_ID%20%3D%20'"
+ gisId
+ "'&returnGeometry=false&outFields=CLOSED_GIS_ID%2CREDIRECT_GIS_ID";
request(redirectUrl, function (err, res, body) {
if (!err && res.statusCode === 200) {
gisId = json.features[0].attributes["REDIRECT_GIS_ID"],
match = gisId.match(/dcps_(.*)/);
if (match) { session.zonedSchools.push(parseInt(match[1])); }
}
done();
});
}
}
});
next();
} else {
next();
done();
}
});
var Session = mongoose.model('Session', SessionSchema);
// Routes
app.post('/api/dcgis', function (req, res) {
var url = 'http://dcatlas.dcgis.dc.gov/wsProxy/proxy_LocVerifier.asmx/findLocation_all',
str = req.body.address;
request.post(url, {form: {str: str}}).pipe(res);
});
app.get('/api/sessions/:hashid', function (req, res) {
return Session.findByHashid(req.params.hashid, function (err, session) {
if (!err) {
return res.send(session);
} else {
return console.log(err);
}
});
});
app.post('/api/sessions', function (req, res) {
var session = new Session({
grade: req.body.grade,
address: req.body.address,
addressGISValid: req.body.addressGISValid,
xcoord: req.body.xcoord,
ycoord: req.body.ycoord,
neighborhoodCluster: req.body.neighborhoodCluster,
zonedSchools: req.body.zonedSchools,
rankings: req.body.rankings
});
return session.save(function (err) {
if (err) { console.log(err); }
return res.send(session);
});
});
app.put('/api/sessions/:hashid', function (req, res) {
return Session.findByHashid(req.params.hashid, function (err, session) {
session.grade = req.body.grade;
session.address = req.body.address;
session.addressGISValid = req.body.addressGISValid;
session.xcoord = req.body.xcoord;
session.ycoord = req.body.ycoord;
session.neighborhoodCluster = req.body.neighborhoodCluster;
session.zonedSchools = req.body.zonedSchools;
session.rankings = req.body.rankings;
return session.save(function (err) {
if (err) { console.log(err); }
return res.send(session);
});
});
});
// Start server
var port = process.env.PORT || 5000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});