-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingular.js
More file actions
executable file
·69 lines (55 loc) · 1.46 KB
/
singular.js
File metadata and controls
executable file
·69 lines (55 loc) · 1.46 KB
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
const Router = require('@koa/router');
const save = require('./save');
module.exports = (db, key, opts) => {
const router = new Router();
return router
.get(get)
.post(post, save(db)) // create
.put(put, save(db)) // replace
.patch(patch, save(db)) // update
.routes();
async function get(ctx, next) {
ctx.body = db.get(key);
await next();
}
async function post(ctx, next) {
ctx.status = 409;
ctx.body = { error: "Already exists, use PUT to replace" };
await next();
}
// not well-tested
async function put(ctx, next) {
let validate = db.getValidate(key);
if (!validate(ctx.request.body)) {
ctx.body = {
resource: ctx.request.body,
errors: validate.errors
};
ctx.status = 400;
} else {
db.set(key, ctx.request.body);
ctx.body = ctx.request.body;
}
await next();
}
// not well-tested
async function patch(ctx, next) {
let existingResource = db.getById(key, ctx.request.body.id);
if (!existingResource) {
ctx.throw(404);
}
let newResource = Object.assign(_.cloneDeep(existingResource), ctx.request.body);
let validate = db.getValidate(key);
if (!validate(newResource)) {
ctx.body = {
resource: newResource,
errors: validate.errors
};
ctx.status = 400;
} else {
db.update(key, ctx.request.body);
ctx.body = db.getById(key, ctx.request.body.id);
}
await next();
}
};