-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
111 lines (87 loc) · 3.04 KB
/
routes.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
'use strict'
const validation = require("./validate")
module.exports = function(ctx) {
// extract context from passed in object
const db = ctx.db,
server = ctx.server
// assign collection to variable for further use
const collection = db.collection('points')
/**
* Create
*/
server.post('/points', (req, res, next) => {
if(validation.validatePoint(req.body)){
// extract data from body and add timestamps
const data = Object.assign({}, req.body, {
created: new Date(),
updated: new Date(),
verified: false
})
// insert one object into points collection
collection.insertOne(data)
.then(doc => res.send(200, doc.ops[0]))
.catch(err => res.send(500, err))
next()
}else{
res.send(400, validation.whyInvalidPoint(req.body))
}
})
/**
* Read
*/
server.get('/', (req, res, next) => {
var body = '<html><body><h3>This is the VUEFinder REST server.</h3><a href="https://github.com/sufyanAbbasi/vue-finder-rest-api" target="_blank">Github</a></body></html>';
res.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/html'
});
res.write(body);
res.end();
})
// returns all the points
server.get('/points', (req, res, next) => {
// find points and convert to array (with optional query, skip and limit)
collection.find(req.query || {}).toArray()
.then(docs => res.send(200, docs))
.catch(err => res.send(500, err))
next()
})
// returns a list of unique categories
server.get('/points/categories', (req, res, next) => {
// find points and convert to array (with optional query, skip and limit)
collection.distinct("category")
.then(docs => res.send(200, docs))
.catch(err => res.send(500, err))
})
/**
* Update
*/
server.put('/points/:id', (req, res, next) => {
// extract data from body and add timestamps
const data = Object.assign({}, req.body, {
updated: new Date()
})
// build out findOneAndUpdate variables to keep things organized
let query = { _id: req.params.id },
body = { $set: data },
opts = {
returnOriginal: false,
upsert: true
}
// find and update document based on passed in id (via route)
collection.findOneAndUpdate(query, body, opts)
.then(doc => res.send(204))
.catch(err => res.send(500, err))
next()
})
/**
* Delete
*/
server.del('/points/:id', (req, res, next) => {
// remove one document based on passed in id (via route)
collection.findOneAndDelete({ _id: req.params.id })
.then(doc => res.send(204))
.catch(err => res.send(500, err))
next()
})
}