-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
245 lines (227 loc) · 7.57 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
const express = require('express');
const helmet = require('helmet');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const request = require('request-promise');
const schemas = require('./utilities/schemas');
const config = require('./config.json');
const query = require('./utilities/query-utilities');
mongoose.connect(config.databaseURL, config.mongooseConfig).catch((err) => {
gracefulShutdown(err);
});
mongoose.connection.on('connected', () => {
console.log(`connected to: ${config.databaseURL}`);
});
mongoose.connection.on('error', (err) => {
console.log(`Mongoose connection error: ${err}`);
gracefulShutdown(err);
});
mongoose.connection.on('disconnected', () => {
console.log('Mongoose disconnected, trying to reconnect');
mongoose.connect(config.databaseURL, config.mongooseConfig).then().catch((err) => {
console.log('reconnection attempt failed, shutting down');
gracefulShutdown(err);
});
});
function isEmpty(obj) {
for(let key in obj) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}
const app = express();
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(helmet());
app.use((req, res, next) => {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); // Request headers you wish to allow
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');
next();
});
app.get('/search', async (req, res, next) => {
if (isEmpty(req.query)) {
const err = new Error('require stat or cardName');
err.statusCode = 400;
return next(err);
if (!req.query.stat && !req.query.cardName) {
const err = new Error('require stat or cardName');
err.statusCode = 400;
return next(err);
}
}
if (req.query.stat) {
const result = [];
try {
let temp = await query.queryHighestMadeMyDay(schemas.Cards);
result.push(temp[0]);
temp = await query.queryHighestChangeMyLife(schemas.Cards);
result.push(temp[0]);
temp = await query.queryHighestFaithInHuman(schemas.Cards);
result.push(temp[0]);
temp = await query.queryHighestMeh(schemas.Cards);
result.push(temp[0]);
temp = await query.queryHighestNice(schemas.Cards);
result.push(temp[0]);
temp = await query.queryHighestLoved(schemas.Cards);
result.push(temp[0]);
temp = await query.queryHighestHistory(schemas.Cards);
result.push(temp[0]);
res.jsonp(result);
} catch (err) {
next(err);
}
} else if (req.query.cardName) {
try {
const result = [];
if (req.query.oneOnly) {
let temp = await query.queryCardByCardNameOne(schemas.Cards, req.query.cardName);
result.push(temp);
res.jsonp(result);
} else {
let temp = await query.queryCardByCardName(schemas.Cards, req.query.cardName);
res.jsonp(temp);
}
} catch (err) {
next(err);
}
}
});
app.post('/submit/', async (req, res, next) => {
const err = new Error('body cannot be empty request');
err.statusCode = 400;
if (!req.body) {
return next(err);
}
if (!req.body.name) {
const err = new Error('require name');
err.statusCode = 400;
return next(err);
}
if (!req.body.history) {
const err = new Error('require history object');
err.statusCode = 400;
return next(err);
}
if (req.body.name === 'fail_sentiment') {
const err = new Error('sentiment failed');
err.statusCode = 400;
return next(err);
}
let history;
try {
history = JSON.parse(req.body.history);
} catch (err) {
return next(err);
}
// find the object
try {
let temp = await query.queryCardByCardNameOne(schemas.Cards, req.body.name);
if (!temp){
return res.send(403, "card not found");
}
let tempURL = `http://127.0.0.1:5000/user/${history.story}`;
let encoded = encodeURI(tempURL);
let options = {
uri: encoded,
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
let fail = false;
await request(options)
.then(function (data) {
console.log('reply', data);
if (!data){
fail = true;
return res.send(209, "extreme negativity detected");
}
})
.catch(function (err) {
console.log(err);
});
if(fail){
return;
}
let rate = history.sentiment;
temp.number_of_pass += 1;
if ((rate & 0x1) === 0x1) {
temp["num_meh"] += 1;
}
if ((rate & 0x2) === 0x2) {
temp["num_what_a_kind_jesture"] += 1;
}
if ((rate & 0x4) === 0x4) {
temp["num_made_me_feel_loved"] += 1;
}
if ((rate & 0x8) === 0x8) {
temp["num_restored_my_faith_in_humanity"] += 1;
}
if ((rate & 0x10) === 0x10) {
temp["num_changed_my_life"] += 1;
}
if ((rate & 0x20) === 0x20) {
temp["num_made_my_day"] += 1;
}
if (history.location) {
temp.last_known_location = history.location;
}
temp.history.push(history);
schemas.Cards.findOneAndUpdate({name: temp.name},temp , {upsert:true}, function(err, doc){
if (err) return res.send(500, { error: err });
return res.send("succesfully saved");
});
} catch (err) {
next(err);
}
});
app.use((err, req, res, next) => {
if (err.statusCode) {
res.status(err.statusCode).send(err.message);
} else if (err.code) {
res.status(err.code).send(err.message);
} else {
res.status(500).send(err.message);
}
next();
});
const server = app.listen(config.port, () => {
console.log(`Listening on port ${config.port}`);
});
function gracefulShutdown(msg) {
mongoose.connection.close(() => {
console.log(`Database connection closed with message, ${msg}`);
});
server.close(() => {
console.log('Express closed.');
});
process.exit(1);
}
process.on('SIGINT', () => {
server.close(() => {
console.log('Express closed.');
// none forcefully try to shutdown mongoose
mongoose.connection.close(false, () => {
console.log('MongoDb default connection closed.');
process.exit(1);
});
});
});
process.on('SIGHUP', () => {
server.close(() => {
console.log('Express closed.');
// none forcefully try to shutdown mongoose
mongoose.connection.close(false, () => {
console.log('MongoDb default connection closed.');
process.exit(1);
});
});
});