1
0
Fork 0
mirror of synced 2024-06-09 14:04:53 +12:00
budibase/packages/server/src/api/routes/public/utils/Endpoint.ts

52 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-02-25 04:13:14 +13:00
import Router from "koa-router"
export type CtxFn = (ctx: any, next?: any) => void | Promise<any>
2022-02-25 04:13:14 +13:00
class Endpoint {
2022-02-25 04:13:14 +13:00
method: string
url: string
controller: CtxFn
middlewares: CtxFn[]
outputMiddlewares: CtxFn[]
2022-02-25 04:13:14 +13:00
constructor(method: string, url: string, controller: CtxFn) {
this.method = method
this.url = url
this.controller = controller
this.middlewares = []
this.outputMiddlewares = []
}
2022-02-25 04:13:14 +13:00
addMiddleware(middleware: CtxFn) {
this.middlewares.push(middleware)
2022-02-25 01:03:46 +13:00
return this
}
addOutputMiddleware(middleware: CtxFn) {
this.outputMiddlewares.push(middleware)
return this
}
2022-02-25 04:13:14 +13:00
apply(router: Router) {
const method = this.method,
url = this.url
const middlewares = this.middlewares,
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
router[method](...params)
}
}
2022-02-25 04:13:14 +13:00
export default Endpoint