forked from raimohanska/turtle-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturtlestore.js
45 lines (42 loc) · 1.3 KB
/
turtlestore.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
var Bacon = require("baconjs")
var randomstring = require("randomstring")
function TurtleStore(conn, app) {
var turtles = conn.collection("turtle")
app.get("/turtles", function(req, res) {
sendResult(mongoFind({}), res)
})
app.get("/turtles/:author", function(req, res) {
sendResult(mongoFind({"content.author": req.params.author}), res)
})
app.get("/turtle/:id", function(req, res) {
sendResult(mongoFind({"id": req.params.id}).map(".0"), res)
})
app.get("/turtle/:author/:name", function(req, res) {
sendResult(mongoFind({"content.author": req.params.author, "content.description": req.params.name}).map(".0"), res)
})
app.post("/turtle", function(req, res) {
var data = {
id: randomstring.generate(10),
content: req.body,
date: new Date()
}
sendResult(mongoPost(data).map(data), res)
})
function mongoPost(data) {
return Bacon.fromNodeCallback(turtles, "insert", [data])
}
function mongoFind(query) {
return Bacon.fromNodeCallback(turtles.find(query).sort({date: -1}), "toArray")
}
function sendResult(resultE, res) {
resultE.onError(res, "send")
resultE.onValue(function(value) {
if (value) {
res.json(value)
} else {
res.status(404).send("Not found")
}
})
}
}
module.exports = TurtleStore