-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
68 lines (57 loc) · 1.53 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
import restify from 'restify';
import Promise from 'bluebird';
import MongoDB, { ObjectId } from 'mongodb';
Promise.promisifyAll(restify);
Promise.promisifyAll(MongoDB);
const { PORT, DB_URI, DB_NAME } = process.env;
const server = restify.createServer();
let db;
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.get('/plants', (req, res, next) => {
db.collection('plants').find({}).toArray().then((plants) => {
res.send(plants);
next();
});
});
server.get('/plants/:id', (req, res, next) => {
db.collection('plants').findOne(
{ _id: ObjectId(req.params.id) }
).then((plants) => {
res.send(plants);
next();
});
});
server.post('/plants', (req, res, next) => {
db.collection('plants').insertOne(
{ name: req.body.name, age: req.body.age }
).then((plant) => {
res.send(plant.ops[0]);
next();
});
});
server.put('/plants/:id', (req, res, next) => {
db.collection('plants').findOneAndUpdate(
{ _id: ObjectId(req.params.id) },
{ $set: { name: req.body.name, age: req.body.age } },
{ returnOriginal: false }
).then(({ value: plant }) => {
res.send(plant);
next();
});
});
server.del('/plants/:id', (req, res, next) => {
db.collection('plants').findOneAndDelete(
{ _id: ObjectId(req.params.id) }
).then(({ value: plant }) => {
res.send(plant);
next();
});
});
Promise.all([
MongoDB.MongoClient.connect(`${DB_URI}/${DB_NAME}`),
server.listen(PORT)
]).spread((_db) => {
db = _db;
console.log(`${server.name} listening at ${server.url}`);
})