forked from daiogo/smartfare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmartfare.js
executable file
·223 lines (185 loc) · 6.28 KB
/
smartfare.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
/*
SmartFare webservice
*/
// Imports modules
var express = require('express'); // Express.js
var mongoose = require('mongoose'); // mongoose (MongoDB driver)
var bodyparser = require('body-parser'); // body-parser (parse HTTP request body)
var eventSchema = require('./db/schemas/event');
var userSchema = require('./db/schemas/user');
var vehicleSchema = require('./db/schemas/vehicle');
// Connects mongoose to mongodb service
mongoose.connect('mongodb://smartfare:[email protected]:55490/smartfare-web');
// Creates mongoose models for each schema
// Parameters are: model name, schema, collection name
var Event = mongoose.model('Event', eventSchema, 'events');
var User = mongoose.model('User', userSchema, 'users');
var Vehicle = mongoose.model('Vehicle', vehicleSchema, 'vehicles');
// Export API methods
module.exports = function() {
// Creates and Express.js app
var app = express();
// Makes app able to use the body-parser module functionality
app.use(bodyparser.json());
convertGPS = function(latLon){
// console.log(latLon);
var number = latLon.split(' ');
var tempLatLon = number[0].toString();
tempLatLon = tempLatLon.split('.');
// console.log(tempLatLon[0]);
var tempLatLonLastTwo = tempLatLon[0].slice(-2)+'.'+ tempLatLon[1];
tempLatLonLastTwo = (Number(tempLatLonLastTwo)*100)/100;
var tempLatLonFirst = parseInt(tempLatLon[0].slice(0,-2));
// console.log(tempLatLonFirst);
var initValue = tempLatLonFirst+(tempLatLonLastTwo/60);
if(number[1] == 'S' || number[1] == 'W') {
initValue = (-1) * initValue;
}
return initValue;
}
app.use(express.static(__dirname + '/public'));
// REQUEST HANDLER: Return events
app.get('/api/trips', function(req, res) {
// Creates mongodb query based on request parameters (located on query string)
/*var departFlightQuery = {
origin: req.query.origin,
destination: req.query.destination,
departureDate: req.query.departureDate,
availableSeats: { $gte: req.query.numberOfPassengers }
}*/
// Query the trip database and executes callback function passed
// as parameter to send response after the query has been completed
Event.find({}, function(error, docs) {
if (error) {
console.log(error);
}
// Gets query results and send response in a JSON format
res.send(docs);
});
});
// REQUEST HANDLER: Return trips
app.get('/api/vehicles', function(req, res) {
// Creates mongodb query based on request parameters (located on query string)
/*var departFlightQuery = {
origin: req.query.origin,
destination: req.query.destination,
departureDate: req.query.departureDate,
availableSeats: { $gte: req.query.numberOfPassengers }
}*/
// Query the trip database and executes callback function passed
// as parameter to send response after the query has been completed
Vehicle.find({}, function(error, docs) {
if (error) {
console.log(error);
}
// Gets query results and send response in a JSON format
var searchResults = require('util').inspect(docs);//JSON.stringify(
res.send(docs);
});
});
// REQUEST HANDLER: Return trips
app.get('/api/users', function(req, res) {
// Creates mongodb query based on request parameters (located on query string)
/*var departFlightQuery = {
origin: req.query.origin,
destination: req.query.destination,
departureDate: req.query.departureDate,
availableSeats: { $gte: req.query.numberOfPassengers }
}*/
// Query the trip database and executes callback function passed
// as parameter to send response after the query has been completed
User.find({}, function(error, docs) {
if (error) {
console.log(error);
}
// Gets query results and send response in a JSON format
var searchResults = require('util').inspect(docs);
res.send(docs);
});
});
// REQUEST HANDLER: Update database
app.post('/api/update', function(req, res) {
// console.log('REQUEST BODY: ');
// console.log(req.body);
var lat = convertGPS(req.body.latitude);
var long = convertGPS(req.body.longitude);
// console.log(lat);
// console.log(long);
var receivedEvent = new Event({
timestamp: req.body.timestamp,
vehicleId: req.body.vehicleId,
userId: req.body.userId,
eventType: req.body.eventType,
balance: req.body.balance / 100 , // Value in cents
latitude: lat,
longitude: long
});
// console.log(receivedEvent);
receivedEvent.save(function(error) {
if (error) {
console.log(error);
res.send('error');
} else {
res.send('ok');
console.log('Saved event!');
//res.send("ok");
}
});
// Queries for vehicle to update onBoard users
Vehicle.findOne( { vehicleId: req.body.vehicleId }, function(error, doc) {
if (error) {
console.log(error);
// res.send("Vehicle doesn't exist");
} else {
console.log(doc);
const userIndex = doc.onBoardUsers.indexOf(req.body.userId);
if (req.body.eventType == 0) {
// boarding event
if(userIndex < 0) {
// Add user to vehicle array
doc.onBoardUsers.push(req.body.userId);
doc.save();
console.log('New user onboard');
}
} else {
// offboarding event
if (userIndex >= 0) {
// Remove user from vehicle array
doc.onBoardUsers.splice(userIndex,1);
doc.save();
console.log('User removed from vehicle');
}
}
// res.send("ok");
}
});
// // Queries for user to be updated
// User.findOne( { uid: req.body.userId }, function(error, doc) {
// if (error) {
// console.log(error);
// res.send("User doesn't exist");
// } else {
// console.log(doc);
// doc.balance = req.body.balance; // Or -= req.body.fare
// doc.save();
// console.log('Saved new balance!');
// res.send("ok");
// }
// });
});
/* =====================FRONT END ROUTES=====================*/
// Index page
app.get('/', function(req, res) {
res.sendFile('/public/index.html'); // load our public/index.html file
});
app.get('/admin/events', function(req, res) {
res.sendFile(__dirname + '/public/views/tripsView.html');
});
app.get('/admin/users', function(req, res) {
res.sendFile(__dirname + '/public/views/usersView.html');
});
app.get('/admin/vehicles', function(req, res) {
res.sendFile(__dirname + '/public/views/vehiclesView.html');
});
return app;
}