-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathexamples.js
63 lines (55 loc) · 1.56 KB
/
examples.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
'use strict';
const controller = require('lib/wiring/controller');
const models = require('app/models');
const Example = models.example;
const authenticate = require('./concerns/authenticate');
const setUser = require('./concerns/set-current-user');
const setModel = require('./concerns/set-mongoose-model');
const index = (req, res, next) => {
Example.find()
.then(examples => res.json({
examples: examples.map((e) =>
e.toJSON({ virtuals: true, user: req.user })),
}))
.catch(next);
};
const show = (req, res) => {
res.json({
example: req.example.toJSON({ virtuals: true, user: req.user }),
});
};
const create = (req, res, next) => {
let example = Object.assign(req.body.example, {
_owner: req.user._id,
});
Example.create(example)
.then(example =>
res.status(201)
.json({
example: example.toJSON({ virtuals: true, user: req.user }),
}))
.catch(next);
};
const update = (req, res, next) => {
delete req.body._owner; // disallow owner reassignment.
req.example.update(req.body.example)
.then(() => res.sendStatus(204))
.catch(next);
};
const destroy = (req, res, next) => {
req.example.remove()
.then(() => res.sendStatus(204))
.catch(next);
};
module.exports = controller({
index,
show,
create,
update,
destroy,
}, { before: [
{ method: setUser, only: ['index', 'show'] },
{ method: authenticate, except: ['index', 'show'] },
{ method: setModel(Example), only: ['show'] },
{ method: setModel(Example, { forUser: true }), only: ['update', 'destroy'] },
], });