/* eslint-disable @typescript-eslint/ban-ts-comment */ import KoaRouter from '@koa/router' import Koa from 'koa' import { OpenApiManager } from '../openapi/manager/OpenApiManager' import { ExtractedRequestParams } from '../utils/TypeUtils' import { responseValueToJson } from './responseValueToJson' type Props = { skipOpenApiAnalysis: boolean } export class Router { public koaRouter: KoaRouter = new KoaRouter() public constructor(props: Props = { skipOpenApiAnalysis: false }) { if (!props.skipOpenApiAnalysis) { const openApiManager = OpenApiManager.getInstance() openApiManager.registerRouters([this]) } } public use(...middleware: Array>) { // @ts-ignore this.koaRouter.use(...middleware) return this } public with>( middleware: (ctx: Koa.ParameterizedContext) => ResponseTypeT ) { type AugmentedData = ResponseTypeT extends Promise ? Awaited : ResponseTypeT this.koaRouter.use(async (ctx, next) => { // @ts-ignore const userData = await Promise.resolve(middleware(ctx)) Object.keys(userData).forEach((key) => { ctx[key] = userData[key] }) await next() }) return this as Router } public get

( path: P, callback: KoaRouter.Middleware> ) { this.koaRouter.get(path, async (ctx) => { // @ts-ignore const responseValue = await callback(ctx, undefined) ctx.body = responseValueToJson(responseValue) }) return this } public post

( path: P, callback: KoaRouter.Middleware> ) { this.koaRouter.post(path, async (ctx) => { // @ts-ignore const responseValue = await callback(ctx, undefined) ctx.body = responseValueToJson(responseValue) }) return this } public put

( path: P, callback: KoaRouter.Middleware> ) { this.koaRouter.put(path, async (ctx) => { // @ts-ignore const responseValue = await callback(ctx, undefined) ctx.body = responseValueToJson(responseValue) }) return this } public delete

( path: P, callback: KoaRouter.Middleware> ) { this.koaRouter.delete(path, async (ctx) => { // @ts-ignore const responseValue = await callback(ctx, undefined) ctx.body = responseValueToJson(responseValue) }) return this } public del

( path: P, callback: KoaRouter.Middleware> ) { this.koaRouter.del(path, async (ctx) => { // @ts-ignore const responseValue = await callback(ctx, undefined) ctx.body = responseValueToJson(responseValue) }) return this } public patch

( path: P, callback: KoaRouter.Middleware> ) { this.koaRouter.patch(path, async (ctx) => { // @ts-ignore const responseValue = await callback(ctx, undefined) ctx.body = responseValueToJson(responseValue) }) return this } public routes() { return this.koaRouter.routes() } public allowedMethods() { return this.koaRouter.allowedMethods() } }