import { BaseFramework, CommonFilterUnion, CommonMiddlewareUnion, HTTP_SERVER_KEY, IMidwayBootstrapOptions, PathFileUtils, RouterInfo, WebControllerGenerator, MidwayConfigMissingError, httpError, MidwayWebRouterService, MidwayTraceService, Framework, Types, } from '@midwayjs/core'; import { Cookies } from '@midwayjs/cookies'; import { Context, IMidwayKoaApplication, IMidwayKoaConfigurationOptions, IMidwayKoaContext, } from './interface'; import * as Router from '@koa/router'; import type { DefaultState, Middleware, Next } from 'koa'; import * as koa from 'koa'; import { Server } from 'http'; import { setupOnError } from './onerror'; import * as qs from 'qs'; import * as querystring from 'querystring'; import { getFreePort } from './utils'; const COOKIES = Symbol('context#cookies'); class KoaControllerGenerator extends WebControllerGenerator { constructor( readonly app, readonly webRouterService: MidwayWebRouterService ) { super(app, webRouterService); } createRouter(routerOptions: any): Router { const router = new Router(routerOptions); router.prefix(routerOptions.prefix); return router; } generateController(routeInfo: RouterInfo) { return this.generateKoaController(routeInfo); } } @Framework() export class MidwayKoaFramework extends BaseFramework< IMidwayKoaApplication, IMidwayKoaContext, IMidwayKoaConfigurationOptions, Next > { private server: Server; private generator: KoaControllerGenerator; private webRouterService: MidwayWebRouterService; configure(): IMidwayKoaConfigurationOptions { return this.configService.getConfiguration('koa'); } async applicationInitialize(options: Partial) { const appKeys = this.configService.getConfiguration('keys') || this.configurationOptions['keys']; if (!appKeys) { throw new MidwayConfigMissingError('config.keys'); } const cookieOptions = this.configService.getConfiguration('cookies'); const cookieGetOptions = this.configService.getConfiguration( 'cookiesExtra.defaultGetOptions' ); this.app = new koa({ keys: [].concat(appKeys), proxy: this.configurationOptions.proxy, proxyIpHeader: this.configurationOptions.proxyIpHeader, subdomainOffset: this.configurationOptions.subdomainOffset, maxIpsCount: this.configurationOptions.maxIpsCount, }) as IMidwayKoaApplication; Object.defineProperty(this.app.context, 'cookies', { get() { if (!this[COOKIES]) { this[COOKIES] = new Cookies( this, this.app.keys, cookieOptions, cookieGetOptions ); } return this[COOKIES]; }, enumerable: true, }); Object.defineProperty(this.app.context, 'locals', { get() { return this.state; }, set(value) { this.state = value; }, }); Object.defineProperty(this.app.context, 'forward', { get() { return async function (this: Context, url: string) { const routerService = this.requestContext.get(MidwayWebRouterService); const matchedUrlRouteInfo = await routerService.getMatchedRouterInfo( url, this.method ); if (matchedUrlRouteInfo) { if (matchedUrlRouteInfo.controllerClz) { // normal class controller router const controllerInstance = await this.requestContext.getAsync( matchedUrlRouteInfo.controllerClz ); return controllerInstance[matchedUrlRouteInfo.method as string]( this ); } else if (typeof matchedUrlRouteInfo.method === 'function') { // dynamic router return matchedUrlRouteInfo.method(this); } } else { throw new httpError.NotFoundError(`Forward url ${url} Not Found`); } }; }, }); const converter = this.configurationOptions.queryParseMode === 'strict' ? function (value) { return !Array.isArray(value) ? [value] : value; } : this.configurationOptions.queryParseMode === 'first' ? function (value) { return Array.isArray(value) ? value[0] : value; } : undefined; // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; // fix query with array params Object.defineProperty(this.app.request, 'query', { get() { const str = this.querystring; const c = (this._querycache = this._querycache || {}); // find cache if (c[str]) return c[str]; if (self.configurationOptions.queryParseMode) { // use qs module to parse query const parseOptions: qs.IParseOptions = { ...self.configurationOptions.queryParseOptions, ...(self.configurationOptions.queryParseMode === 'first' ? { duplicates: 'first' } : {}), }; c[str] = qs.parse(str, parseOptions); } else { // use querystring to parse query by default c[str] = querystring.parse(str); } if (converter) { for (const key in c[str]) { c[str][key] = converter(c[str][key]); } } return c[str]; }, set(value) { this._querycache = this._querycache || {}; this._querycache[this.querystring] = value; }, }); const onerrorConfig = this.configService.getConfiguration('onerror'); setupOnError(this.app, onerrorConfig, this.logger); // not found middleware const notFound = async (ctx, next) => { await next(); if (!ctx._matchedRoute && ctx.body === undefined) { throw new httpError.NotFoundError(`${ctx.path} Not Found`); } }; const applyMiddlewares = [notFound]; // versioning middleware const versioningConfig = this.configurationOptions.versioning; if (versioningConfig?.enabled) { applyMiddlewares.push(this.createVersioningMiddleware(versioningConfig)); } // root middleware const midwayRootMiddleware = async (ctx, next) => { this.app.createAnonymousContext(ctx); const traceService = this.applicationContext.get(MidwayTraceService); const spanName = `${ctx.method} ${ctx.path || '/'}`; const traceMetaResolver = (this.configurationOptions as any)?.tracing ?.meta; const traceEnabled = (this.configurationOptions as any)?.tracing?.enable !== false; const traceExtractor = (this.configurationOptions as any)?.tracing ?.extractor; const traceInjector = (this.configurationOptions as any)?.tracing ?.injector; const requestCarrier = typeof traceExtractor === 'function' ? traceExtractor({ ctx, request: ctx.request, response: ctx.response, }) : ctx.headers; const responseCarrier = typeof traceInjector === 'function' ? traceInjector({ ctx, request: ctx.request, response: ctx.response }) : ctx.response.res; await traceService.runWithEntrySpan( spanName, { enable: traceEnabled, carrier: requestCarrier, responseCarrier, attributes: { 'midway.protocol': 'http', }, meta: traceMetaResolver, metaArgs: { ctx, carrier: requestCarrier, request: ctx.request, response: ctx.response, }, }, async () => { await ( await this.applyMiddleware(applyMiddlewares) )(ctx, next); if ( ctx.body === undefined && !ctx.response._explicitStatus && ctx._matchedRoute ) { // 如果进了路由,重新赋值,防止 404 ctx.body = undefined; } } ); }; this.app.use(midwayRootMiddleware); this.webRouterService = await this.applicationContext.getAsync( MidwayWebRouterService, [ { globalPrefix: this.configurationOptions.globalPrefix, }, ] ); this.generator = new KoaControllerGenerator( this.app, this.webRouterService ); this.defineApplicationProperties({ generateController: this.generateController.bind(this), getPort: this.getPort.bind(this), }); // hack use method (this.app as any).originUse = this.app.use; this.app.use = this.app.useMiddleware as any; } async loadMidwayController() { await this.generator.loadMidwayController(newRouter => { const dispatchFn = newRouter.middleware(); (dispatchFn as any)._name = `midwayController(${ newRouter?.opts?.prefix || '/' })`; this.app.use(dispatchFn); }); } /** * wrap controller string to middleware function */ public generateController( routeInfo: RouterInfo ): Middleware { return this.generator.generateKoaController(routeInfo); } public async run(): Promise { // load controller await this.loadMidwayController(); // restore use method this.app.use = (this.app as any).originUse; const serverOptions = { ...this.configurationOptions, ...this.configurationOptions.serverOptions, }; // https config if (serverOptions.key && serverOptions.cert) { serverOptions.key = PathFileUtils.getFileContentSync(serverOptions.key); serverOptions.cert = PathFileUtils.getFileContentSync(serverOptions.cert); serverOptions.ca = PathFileUtils.getFileContentSync(serverOptions.ca); process.env.MIDWAY_HTTP_SSL = 'true'; if (serverOptions.http2) { this.server = require('http2').createSecureServer( serverOptions, this.app.callback() ); } else { this.server = require('https').createServer( serverOptions, this.app.callback() ); } } else { if (serverOptions.http2) { this.server = require('http2').createServer( serverOptions, this.app.callback() ); } else { this.server = require('http').createServer( serverOptions, this.app.callback() ); } } // register httpServer to applicationContext this.applicationContext.registerObject(HTTP_SERVER_KEY, this.server); // server timeout if (Types.isNumber(this.configurationOptions.serverTimeout)) { this.server.setTimeout(this.configurationOptions.serverTimeout); } this.configurationOptions.listenOptions = { port: this.configurationOptions.port, host: this.configurationOptions.hostname, ...this.configurationOptions.listenOptions, }; // set port and listen server let customPort: string | number = process.env.MIDWAY_HTTP_PORT || this.configurationOptions.listenOptions.port; if (customPort === 0 || customPort === '0') { customPort = await getFreePort(); this.logger.info( `[midway:koa] server has auto-assigned port ${customPort}` ); } this.configurationOptions.listenOptions.port = Number(customPort); if (this.configurationOptions.listenOptions.port) { new Promise(resolve => { // 使用 ListenOptions 对象启动服务器 this.server.listen(this.configurationOptions.listenOptions, () => { resolve(); }); // 设置环境变量 process.env.MIDWAY_HTTP_PORT = String( this.configurationOptions.listenOptions.port ); }); this.logger.debug( `[midway:koa] server is listening on port ${customPort}` ); } } public async beforeStop() { if (this.server) { new Promise(resolve => { this.server.close(resolve); process.env.MIDWAY_HTTP_PORT = ''; }); this.logger.debug('[midway:koa] server is stopped!'); } } public getFrameworkName() { return 'koa'; } public getServer() { return this.server; } public getPort(): string { return process.env.MIDWAY_HTTP_PORT; } public useMiddleware( Middleware: CommonMiddlewareUnion ) { this.middlewareManager.insertLast(Middleware); } public useFilter( Filter: CommonFilterUnion ) { this.filterManager.useFilter(Filter); } private createVersioningMiddleware(config: any) { return async (ctx: IMidwayKoaContext, next: Next) => { // 提取版本信息 const version = this.extractVersion(ctx, config); ctx.apiVersion = version; // 对于 URI 版本控制,重写路径 if (config.type === 'URI' && version) { const versionPrefix = `/${config.prefix || 'v'}${version}`; if (ctx.path.startsWith(versionPrefix)) { ctx.originalPath = ctx.path; ctx.path = ctx.path.replace(versionPrefix, '') || '/'; } } await next(); }; } private extractVersion( ctx: IMidwayKoaContext, config: any ): string | undefined { // 自定义提取函数优先 if (config.extractVersionFn) { return config.extractVersionFn(ctx); } const type = config.type || 'URI'; switch (type) { case 'HEADER': { const headerName = config.header || 'x-api-version'; const headerValue = ctx.headers[headerName]; if (typeof headerValue === 'string') { return headerValue.replace(/^v/, ''); } return undefined; } case 'MEDIA_TYPE': { const accept = ctx.headers.accept; const paramName = config.mediaTypeParam || 'version'; const match = accept?.match(new RegExp(`${paramName}=(\\d+)`)); return match ? match[1] : undefined; } case 'URI': { const prefix = config.prefix || 'v'; const uriMatch = ctx.path.match(new RegExp(`^/${prefix}(\\d+)`)); return uriMatch ? uriMatch[1] : undefined; } default: return config.defaultVersion; } } }