Skip to content

Commit fa51c79

Browse files
committed
initial koa-api implementation
1 parent 4bda8f3 commit fa51c79

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

lib/koa-api/src/koa-api.ts

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import Router, { RouterOptions } from '@koa/router'
2+
import { default as Koa } from 'koa'
3+
import type { NextApiRequest, NextApiResponse } from 'next'
4+
5+
declare module 'koa' {
6+
type IncomingMessage = NextApiRequest
7+
type ServerResponse = NextApiResponse
8+
interface Request extends Koa.BaseRequest {
9+
body?: any
10+
}
11+
}
12+
13+
type KoaOptions = {
14+
env?: string
15+
keys?: string[]
16+
proxy?: boolean
17+
subdomainOffset?: number
18+
proxyIpHeader?: string
19+
maxIpsCount?: number
20+
}
21+
22+
type KoaApiOptions = {
23+
koa?: KoaOptions
24+
attachBody?: boolean
25+
router?: Router.RouterOptions
26+
routerAllowedMethods?: Router.RouterAllowedMethodsOptions
27+
}
28+
29+
export class KoaApi extends Koa {
30+
router: Router
31+
32+
protected firstRun = true
33+
34+
protected options: KoaApiOptions
35+
36+
constructor(options: KoaApiOptions = {}) {
37+
super(options.koa)
38+
39+
const { router: routerOpts = {} } = options || {}
40+
this.options = {
41+
...options,
42+
attachBody: options?.attachBody ?? true,
43+
router: {
44+
...routerOpts,
45+
prefix: routerOpts.prefix ?? '/api'
46+
}
47+
}
48+
49+
this.router = new Router(this.options.router)
50+
if (this.options.attachBody) {
51+
this.use((ctx, next) => {
52+
ctx.request.body = ctx.req.body
53+
next()
54+
})
55+
}
56+
}
57+
58+
run(req: NextApiRequest, res: NextApiResponse) {
59+
if (this.firstRun) {
60+
this.firstRun = false
61+
this.use(this.router.routes()).use(
62+
this.router.allowedMethods(this.options.routerAllowedMethods)
63+
)
64+
}
65+
66+
return this.callback()(req, res)
67+
}
68+
69+
getNewRouter(opts?: RouterOptions) {
70+
return new Router(opts)
71+
}
72+
}
73+
74+
export function withKoaApi(koa: KoaApi) {
75+
return (req: NextApiRequest, res: NextApiResponse) => koa.run(req, res)
76+
}

0 commit comments

Comments
 (0)