2022-02-25 04:13:14 +13:00
|
|
|
import Router from "koa-router"
|
|
|
|
|
2022-03-02 07:35:08 +13:00
|
|
|
export type CtxFn = (ctx: any, next?: any) => void | Promise<any>
|
2022-02-25 04:13:14 +13:00
|
|
|
|
2022-02-23 07:40:09 +13:00
|
|
|
class Endpoint {
|
2022-02-25 04:13:14 +13:00
|
|
|
method: string
|
|
|
|
url: string
|
|
|
|
controller: CtxFn
|
|
|
|
middlewares: CtxFn[]
|
2022-03-02 07:35:08 +13:00
|
|
|
outputMiddlewares: CtxFn[]
|
2022-02-25 04:13:14 +13:00
|
|
|
|
|
|
|
constructor(method: string, url: string, controller: CtxFn) {
|
2022-02-23 07:40:09 +13:00
|
|
|
this.method = method
|
|
|
|
this.url = url
|
|
|
|
this.controller = controller
|
|
|
|
this.middlewares = []
|
2022-03-02 07:35:08 +13:00
|
|
|
this.outputMiddlewares = []
|
2022-02-23 07:40:09 +13:00
|
|
|
}
|
|
|
|
|
2022-02-25 04:13:14 +13:00
|
|
|
addMiddleware(middleware: CtxFn) {
|
2022-02-23 07:40:09 +13:00
|
|
|
this.middlewares.push(middleware)
|
2022-02-25 01:03:46 +13:00
|
|
|
return this
|
2022-02-23 07:40:09 +13:00
|
|
|
}
|
|
|
|
|
2022-03-02 07:35:08 +13:00
|
|
|
addOutputMiddleware(middleware: CtxFn) {
|
|
|
|
this.outputMiddlewares.push(middleware)
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
2022-02-25 04:13:14 +13:00
|
|
|
apply(router: Router) {
|
2022-02-23 07:40:09 +13:00
|
|
|
const method = this.method,
|
|
|
|
url = this.url
|
|
|
|
const middlewares = this.middlewares,
|
2022-03-02 07:35:08 +13:00
|
|
|
controller = this.controller,
|
|
|
|
outputMiddlewares = this.outputMiddlewares
|
|
|
|
// need a function to do nothing to stop the execution at the end
|
|
|
|
// middlewares are circular so if they always keep calling next, it'll just keep looping
|
|
|
|
const complete = () => {}
|
|
|
|
const params = [
|
|
|
|
url,
|
|
|
|
...middlewares,
|
|
|
|
controller,
|
|
|
|
...outputMiddlewares,
|
|
|
|
complete,
|
|
|
|
]
|
2022-02-25 04:13:14 +13:00
|
|
|
// @ts-ignore
|
2022-02-23 07:40:09 +13:00
|
|
|
router[method](...params)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-25 04:13:14 +13:00
|
|
|
export default Endpoint
|