-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcrud.js
61 lines (51 loc) · 1.39 KB
/
crud.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
'use strict';
/**
* Generates generic Koa CRUD controller for a given resource.
*/
var route = require('koa-route'),
_ = require('lodash');
/**
* Register Koa routes on a given Koa app for a given resource.
*/
exports.init = function (app, resource, routeName) {
routeName = '/' + routeName
// handle non-array objects
if (!Array.isArray(resource)) {
app.use(route.get(routeName, function *() {
this.body = resource
}));
return;
}
// list all items filtered by query (if any)
app.use(route.get(routeName, function *() {
this.body = _.filter(resource, this.query)
}));
// get one item by id
app.use(route.get(routeName + '/:id', function *(id) {
var item = _.find(resource, {id: id});
if (!item) {
this.status = 404;
return;
}
this.body = item;
}));
// create new item
app.use(route.post(routeName, function *() {
resource.push(this.request.body);
this.status = 201;
this.body = this.request.body;
}));
// update item by id
app.use(route.put(routeName + '/:id', function *(id) {
var i = _.findIndex(resource, {id: id});
resource[i] = this.request.body;
this.status = 200;
this.body = this.request.body;
}));
// delete item by id
app.use(route.delete(routeName + '/:id', function *(id) {
var i = _.findIndex(resource, {id: id});
resource.splice(i, 1);
this.status = 204;
}));
};