-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
397 lines (360 loc) · 10.8 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
/* Load values from config file for below variables */
var config = require('./config.json');
/* URL to MongoDB store */
var dbUrl = config.dbUrl;
/* MongoDB Database name */
var dbName = config.dbName;
/* HTTP Port for server */
var port = config.port;
/* Init Monk */
var Datastore = require('monk')(dbUrl + '/' + dbName);
var express = require('express'),
app = new express(),
/* Express 4.x body-parse for urlencode and json */
bodyParser = require('body-parser'),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
/* Reduce Socket.IO Logging */
io.set('log level', 1);
/* Express 4.x body-parser for urlencode and json */
app.use(bodyParser());
app.use(function(err, req, res, next) {
'use strict';
res.json(500, {Error: 'Improperly Formatted Request/JSON'});
});
// app.use(express.favicon(__dirname + '/favicon.ico', {
// maxAge: 6000000
// }));
/* For example.html usage. Comment out in production and remove "clientExample" dir */
app.use(express.static(__dirname + '/clientExample', {maxAge: 6000000}));
/* Get item in form of collectionName/item/[key] */
/* curl -X GET -H "Content-Type: application/json" http://localhost:3000/example/test */
/* Supports nested gets in the form of collectionName/item/key/key/key ... */
/* curl -X GET -H "Content-Type: application/json" http://localhost:3000/example/test/data0/data1 */
app.get(/^\/((?:[^\/]+\/?)+)\/?/, function (req, res, next) {
'use strict';
// Called if item in query not found
function notFound(item, key, root) {
var ret = {};
if (item && !key) {
ret['Error'] = 'Item ' + item + ' does not exist';
} else if (!item && key) {
ret['Error'] = 'Key ' + key + ' does not exist';
} else if (item && key && !root) {
ret['Error'] = 'Key ' + key + ' of Item ' + item + ' does not exist';
} else if (item && key && root) {
ret['Error'] = 'Key ' + key + ' of Item ' + item + ' does not exist in ' + root;
} else {
ret['Error'] = 'Item does not exist';
}
return ret;
}
var parm = req.params[0];
if (parm.lastIndexOf('/') === (parm.length -1)) {
parm = parm.slice(0, -1);
}
parm = parm.split('/');
if (parm.length === 1) next();
else {
var db = parm[0];
var item = parm[1];
var key = parm[2];
if (parm.length > 3) {
var keys = [];
for (var i = 3; i < parm.length; i++) {
keys.push(parm[i]);
}
}
itemGet(db, item, function() {
var ret;
if (this.length && !key) {
res.json(this[0]);
} else if (this.length && key && !keys) {
ret = this[0][key];
if (ret === undefined) {
res.json(notFound(item, key));
} else {
res.json(ret);
}
} else if (this.length && key && keys) {
var curr, last, parent;
ret = this[0][key];
if (ret === undefined) {
res.json(notFound(item, key));
} else {
for (var i = 0; i < keys.length; i++) {
curr = keys[i];
ret = ret[keys[i]];
if (ret === undefined) {
break;
}
last = keys[i];
parent = keys[i-1];
}
if (ret === undefined) {
last = last || key;
parent = parent || key;
res.json(notFound(last, curr, parent));
} else {
res.json(ret);
}
}
} else {
res.json(notFound(item));
}
});
}
});
/* Display all items in given collection */
/* curl -X GET -H "Content-Type: application/json" http://localhost:3000/example */
app.get('/:db', function(req, res, next) {
'use strict';
if (Object.keys(req.body).length) {
next();
} else {
var db = req.params.db;
collectionGet(db, function() {
if (!Object.keys(this[Object.keys(this)[0]]).length) {
res.json({Error: 'Database empty or does not exist'});
} else {
res.json(this);
}
});
}
});
/* Find item using query (such as regex example below) in collection */
/* curl -X GET -H "Content-Type: application/json" -d '{ "_id": { "$regex": "tes", "$options": "i" }}' \
http://localhost:3000/example */
app.get('/:db', function(req, res) {
'use strict';
var db = req.params.db;
var query = req.body;
collectionFind(db, query, function() {
if (!Object.keys(this[Object.keys(this)[0]]).length) {
res.json({Error: 'No matches found'});
} else {
res.json(this);
}
});
});
/* Add new item to given collection */
/* curl -X POST -H "Content-Type: application/json" -d '{"_id":"test", "username":"me","password":"pass"}' \
http://localhost:3000/example */
app.post('/:db', function(req, res) {
'use strict';
var db = req.params.db;
var data = req.body;
if(!req.body._id) res.json({Error: 'No _id specified. This is a required field'});
itemAdd(db, data, function() {
if (this) res.json(201, this);
else if (!this) res.json({Error: 'Item already exists. Use PUT method to update item'});
});
});
/* Update existing item in form /collection/item */
/* curl -X PUT -H "Content-Type: application/json" -d '{"username":"em","password":"ssap"}' \
http://localhost:3000/example/test */
app.put('/:db/:item', function(req, res) {
'use strict';
var db = req.params.db;
var item = req.params.item;
var data = req.body;
itemUpdate(db, item, data, function() {
if (this) res.json(this);
else if (!this) res.json({Error: 'Item not found'});
});
});
/* Delete item in form /collection/item */
/* curl -X DELETE -H "Content-Type: application/json" http://localhost:3000/example/test */
/* OR */
/* Clear collection in form /collection */
/* curl -X DELETE -H "Content-Type: application/json" -d '{"clearcollection":"true"}' \
http://localhost:3000/example */
app.delete('/:db/:item?', function(req, res) {
'use strict';
var db = req.params.db;
var item;
if (req.params.item) item = req.params.item;
var itemData = req.body;
if (itemData.hasOwnProperty('clearcollection')) {
if (itemData.clearcollection === 'true') {
collectionClear(db, function() {
res.json({Collection: 'Emptied'});
});
} else {
res.json({Warning: "Set 'clearcollection':'true' if you want to clear the collection"});
}
} else if (item) {
itemRemove(db, item, function() {
var data = {};
data['Removed'] = item;
if (this) res.json(data);
else res.json({Error: 'Item does not exist'});
});
} else {
res.json({Error: 'No item specified for deletion'});
}
});
/* Catchall */
app.get('/*', function(req, res) {
'use strict';
res.json({Error: 'No database specified or invalid command'});
});
/* --- Helper functions --- */
/* Validate JSON to ensure it's properly formatted */
function validateJSON(json) {
'use strict';
try {
JSON.parse(json);
return true;
} catch (e) {
return false;
}
}
/* Get list of items in collection */
function collectionGet(db, cb) {
'use strict';
var collection = Datastore.get(db);
var output = {};
output[db] = {};
collection.find({}, {stream: true})
.each(function(doc) {
output[db][doc._id] = doc;
})
.error(function(err) {
console.error(err);
})
.success(function() {
if (cb) cb.call(output);
});
}
function collectionFind(db, query, cb) {
'use strict';
var collection = Datastore.get(db);
var output = {};
output[db] = {};
collection.find(query, {stream: true})
.each(function(doc) {
output[db][doc._id] = doc;
})
.error(function(err) {
console.error(err);
})
.success(function() {
if (cb) cb.call(output);
});
}
/* Clear all entries in collection and emit clear page */
function collectionClear(db, cb) {
'use strict';
var collection = Datastore.get(db);
collection.remove(function(err) {
if (err) console.error(err);
io.sockets.in(db).emit('clear');
if (cb) cb.call();
});
}
/* Add new items to database and emit new item */
function itemAdd(db, data, cb) {
'use strict';
var collection = Datastore.get(db);
collection.insert(data, function(err, doc) {
if (err && err.code === 11000) {
if (cb) cb.call(false);
} else {
io.sockets.in(db).emit('added', {added: data});
if (cb) cb.call(doc);
}
});
}
/* Fetch specific item */
function itemGet(db, item, cb) {
'use strict';
var collection = Datastore.get(db);
collection.find({_id: item}, function(err, doc) {
if (cb) cb.call(doc);
});
}
/* Edit items in Database and emit change */
function itemUpdate(db, item, data, cb) {
'use strict';
var collection = Datastore.get(db);
var update = {};
update['$set'] = data;
collection.findAndModify({_id: item}, update, function(err, doc) {
if (err) console.error(err);
if (doc) {
io.sockets.in(db).emit('updated', {updated: item});
if (cb) cb.call(doc);
} else {
if (cb) cb.call(false);
}
});
}
/* Remove item from database and emit remove item */
function itemRemove(db, item, cb) {
'use strict';
var collection = Datastore.get(db);
collection.remove({
_id: item
}, function(err, doc) {
if (err) console.error(err);
if (doc === 0) {
if (cb) cb.call(false);
} else {
io.sockets.in(db).emit('removed', {removed: item});
if (cb) cb.call(true);
}
});
}
/* --- Socket.IO Functions --- */
io.sockets.on('connection', function(socket) {
'use strict';
//on connect send a welcome message
socket.emit('message', {text: 'Connected...'});
//on subscription request joins specified room
//later messages are broadcasted on the rooms
socket.on('subscribe', function(data) {
var channel = data.channel;
socket.join(channel);
});
socket.on('collection', function(data) {
var channel = data.channel;
collectionGet(channel, function() {
io.sockets.in(channel).emit('collection', this);
});
});
socket.on('item', function(data) {
var channel = data.channel;
var item = data.item;
itemGet(channel, item, function() {
io.sockets.in(channel).emit('item', this[0]);
});
});
socket.on('remove', function(data) {
var channel = data.channel;
var item = data.item;
itemRemove(channel, item);
});
socket.on('clear', function(data) {
var channel = data.channel;
collectionClear(channel);
});
socket.on('add', function(data) {
var channel = data.channel;
var item = data.item;
//var key = Object.keys(data.item)[0];
itemAdd(channel, item, function() {
if (!this) io.sockets.in(channel).emit('added', {exists: 'Exists'});
});
});
socket.on('update', function(data) {
var channel = data.channel;
var item = data.item[Object.keys(data.item)[0]];
var key = Object.keys(data.item)[0];
itemUpdate(channel, key, item, function() {
if (!this) io.sockets.in(channel).emit('updated', {missing: 'Missing'});
});
});
});
/* Start server on port 3000 */
server.listen(port);