-
Notifications
You must be signed in to change notification settings - Fork 0
/
koa.ts
51 lines (46 loc) · 1.12 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
import { Context, Middleware } from 'koa'
import { useCacheFirst } from './cache'
import { methodDecorator } from './helper'
/**
* @example
* ```ts
* `const koaJson = compose(koaBody, async (ctx, next) => {
* let { body } = ctx.request
* // ...
* await next()
* })
* ```
*/
export function compose(a: Middleware, b: Middleware, ...rest: Middleware[]) {
const ret = async (ctx: Context, next: Next) => {
await a(ctx, async () => {
await b(ctx, next)
})
}
if (rest.length) {
return compose(ret, ...rest)
}
return ret
}
/**
* @description 将约定的controller 包裹为koa的middleware
* @example
* ```ts
* `@koaWrap()
* public static async digestView(ctx: Context): Promise<IDigestResponse> {
* ```
*/
export function koaWrap(): MethodDecorator {
return methodDecorator((controller: Controller) => {
const middleware: Middleware = async (ctx, next) => {
const response = await controller(ctx, next)
if (response != null) {
ctx.body = response
if (response.status) {
ctx.status = response.status
}
}
}
return middleware
})
}