-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·31 lines (24 loc) · 866 Bytes
/
index.js
File metadata and controls
executable file
·31 lines (24 loc) · 866 Bytes
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
const Router = require('@koa/router');
const singular = require('./singular');
const plural = require('./plural');
module.exports = (db, opts) => {
const router = new Router();
router.use(async (ctx, next) => {
if (ctx.query.delay) {
await new Promise(resolve => setTimeout(resolve, ctx.query.delay));
}
await next();
});
for(let [key, value] of Object.entries(db.data)) {
if (Array.isArray(value)) {
// products: [{id:..., name:...},{id:..., name:...}]
router.use(`/${key}`, plural(db, key, opts));
} else if (typeof value === 'object' && value != null) {
// product: {id:..., name:...}
router.use(`/${key}`, singular(db, key, opts));
} else {
throw new Error(`Type of "${key}" (${typeof value}) is not supported. Use objects or arrays of objects.`);
}
}
return router.routes();
};