-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
81 lines (71 loc) · 2.08 KB
/
index.js
File metadata and controls
81 lines (71 loc) · 2.08 KB
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
const Datastore = require("nedb");
const express = require("express");
const jsonParser = require("body-parser").json();
const path = require("path");
let app = express();
let db = {};
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.all(["/:collection/","/:collection/*"], (req, res, next) => {
let collection = req.params.collection;
if (!collection.match(/^[\w\d-]{1,24}$/)) {
console.log(`Bad collection request ${collection}`);
res.status(400);
res.end();
return;
}
console.log(`Checking for collection ${collection}...${!!db[collection]}`);
if (!db[collection]) {
console.log(`Starting new document collection: ${collection}`);
db[collection] = new Datastore({
filename: path.join("./data/", collection, "/db.json"),
autoload: true
});
}
next();
});
app.post("/:collection/", jsonParser, (req, res, next) => {
let collection = req.params.collection;
let document = Object.assign({}, req.body, { "_timestamp": new Date().getTime() });
db[collection].insert(document, (err, saved) => {
if (err) {
res.status(500).json({ error: err.toString() });
next();
}
else {
res.status(201).json(saved);
next();
}
});
});
function list(find, sort, req, res, next) {
let collection = req.params.collection;
db[collection]
.find(find)
.sort(sort)
.exec((err, docs) => {
if (err) {
res.status(500).json({ error: err.toString() });
next();
}
else {
res.json(docs);
next();
}
});
}
app.post("/:collection/_query", jsonParser, (req, res, next) => {
let find = req.body.find || {};
let sort = req.body.sort || { "_timestamp": 1 };
list(find, sort, req, res, next);
});
app.get("/:collection/", (req, res, next) => {
console.log('in get');
list({}, { "_timestamp": 1 }, req, res, next);
});
let port = process.env.HTTP_PORT || 5001;
console.log("Starting server on port " + port);
app.listen(port);