-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
111 lines (97 loc) · 2.59 KB
/
index.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
const log = require('debug')('rest-flat');
const koa = require('koa');
const to = require('koa-path-match')();
const bodyparser = require('koa-bodyparser');
const { v4 } = require('uuid');
module.exports = (flat, app = new koa()) => {
const db = {
index: () => {
return flat.keys().reduce((obj, key) => {
obj[key] = flat.get(key);
return obj;
}, {});
},
has: flat.has.bind(flat),
get: flat.get.bind(flat),
put: (key, value) =>
new Promise(resolve => {
flat.put(key, value, resolve);
}),
del: key => new Promise(resolve => flat.del(key, resolve))
};
app.use(bodyparser());
app.use(async (ctx, next) => {
const start = Date.now();
await next();
log(ctx.method, ctx.path, ctx.status, `${Date.now() - start}ms`);
});
app.use(
to('/', async (ctx, next) => {
switch (ctx.method) {
case 'GET':
ctx.body = await db.index();
break;
case 'POST':
const key = v4();
const { body } = ctx.request;
await db.put(key, body);
ctx.response.set('location', `/${key}`);
ctx.status = 201;
break;
default:
return next();
}
})
);
app.use(
to('/:key', async (ctx, next) => {
const { key } = ctx.params;
const exists = await db.has(key);
switch (ctx.method) {
case 'GET':
ctx.body = await db.get(key);
ctx.status = exists === true ? 200 : 404;
break;
case 'POST':
if (exists) {
ctx.body = await db.get(key);
ctx.status = 409;
} else {
const { body } = ctx.request;
await db.put(key, body);
ctx.response.set('location', `/${key}`);
ctx.status = 201;
}
break;
case 'PUT':
if (exists) {
const { body } = ctx.request;
await db.put(key, body);
ctx.body = body;
ctx.status = 200;
}
break;
case 'PATCH':
if (exists) {
const { body } = ctx.request;
const object = await db.get(key);
const patched = Object.assign({}, object, body);
await db.put(key, patched);
ctx.body = patched;
ctx.status = 200;
}
break;
case 'DELETE':
if (exists) {
ctx.body = await db.get(key);
await db.del(key);
ctx.status = 200;
}
break;
default:
return next();
}
})
);
return app;
};