-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
78 lines (61 loc) · 1.34 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
'use strict';
import 'babel-polyfill';
import Koa from 'koa';
import Router from 'koa-router';
import BodyParser from 'koa-bodyparser';
import { Exceptions, ExceptionHandler } from './exceptions';
const app = new Koa();
const router = Router();
/**
Middlewares
**/
app
// Counting time
.use(async (ctx, next) => {
let start = Date.now();
await next();
console.log(`[${ctx.request.method}][${ctx.request.url}] ${Date.now() - start} ms.`);
})
.use(async (ctx, next) => {
try {
await next();
if (!ctx.body)
throw new Exceptions.NotFound(`Endpoint [${ctx.request.url}] not found.`);
ctx.body = {
ok: true,
content: ctx.body
};
} catch (e) {
ctx.body = ExceptionHandler(e);
}
})
// Body parser
.use(BodyParser())
.use(async (ctx, next) => {
ctx.state = {};
ctx.state.query = ctx.request.query;
ctx.state.body = ctx.request.body;
await next();
})
// routes
.use(router.routes())
// Allowed methods
.use(router.allowedMethods());
/**
Routes
**/
router.get('/', (ctx, next) => {
ctx.body = { hello: "world" };
});
/**
You can use ES7 async/await syntax
router.get('/:name', async (ctx, next) => {
ctx.body = await somethingReturningAPromise();
});
**/
/**
launch
**/
app.listen(3000, () => {
console.log('Listening on port 3000');
});