-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkoa.ts
56 lines (44 loc) · 1.49 KB
/
koa.ts
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
import Application, { Context } from 'koa'
import Router from '@koa/router'
import { getReasonPhrase, StatusCodes } from 'http-status-codes'
import { stripRoute } from '../utils/stripRoute'
import { DefaultJSON, Method } from '../types'
import routes from '../shared/routes'
const router = new Router()
const sendDefaultJSON = (ctx: any, { status, message }: DefaultJSON) => {
ctx.status = status
ctx.body = { status, message }
}
const send = (ctx: any, status: number) => {
ctx.body = ''
ctx.status = status
}
Object.keys(routes).forEach((route): void => {
const variations = routes[route]
const allow: Method[] = []
variations.forEach(
({ method, status = StatusCodes.OK, message, handler }) => {
const _message = message || getReasonPhrase(status)
const _handler = handler
? handler(sendDefaultJSON, send, { isKoa: true })
: (ctx: Context) =>
sendDefaultJSON(ctx.response, { status, message: _message })
if (route.match('teen')) {
// couldn't match the `teen` route group the other way :(
const _routes = stripRoute(route)
_routes.forEach(_route => {
router[method](_route, _handler as Application.Middleware)
})
} else {
router[method](route, _handler as Application.Middleware)
}
allow.push(method)
}
)
router.options(route, ctx => {
ctx.status = 200
ctx.body = ''
ctx.set('Allow', allow.map(s => s.toUpperCase()).join(', '))
})
})
export default router