From 9830a5ce6965814cdd3b35b6648dfa3ec358e9ee Mon Sep 17 00:00:00 2001 From: Aex Date: Tue, 8 Jun 2021 03:41:16 +0000 Subject: [PATCH] Add server export --- .devcontainer.json | 2 +- lib/service/CoaApplication.ts | 18 ++++++++---------- lib/service/CoaHttp.ts | 2 ++ 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.devcontainer.json b/.devcontainer.json index c5a04c2..743b198 100644 --- a/.devcontainer.json +++ b/.devcontainer.json @@ -4,5 +4,5 @@ "name": "coajs", "image": "mcr.microsoft.com/vscode/devcontainers/javascript-node", "postCreateCommand": "yarn", - "extensions": ["mutantdino.resourcemonitor", "esbenp.prettier-vscode", "dbaeumer.vscode-eslint", "eamodio.gitlens"] + "extensions": ["mutantdino.resourcemonitor", "esbenp.prettier-vscode", "dbaeumer.vscode-eslint"] } diff --git a/lib/service/CoaApplication.ts b/lib/service/CoaApplication.ts index c3954b3..297991e 100644 --- a/lib/service/CoaApplication.ts +++ b/lib/service/CoaApplication.ts @@ -1,19 +1,23 @@ import { echo } from 'coa-echo' import { _ } from 'coa-helper' -import { createServer, IncomingMessage, ServerResponse } from 'http' +import { createServer, IncomingMessage, Server, ServerResponse } from 'http' import { CoaRequestBody } from '../base/CoaRequestBody' import { CoaContext, CoaContextConstructor } from './CoaContext' import { CoaRouter } from './CoaRouter' export class CoaApplication { - private readonly router: CoaRouter + public readonly server: Server + public readonly router: CoaRouter private readonly Context: CoaContextConstructor private readonly startAt: bigint = process.hrtime.bigint() constructor(Context: CoaContextConstructor, router: CoaRouter) { + echo.info('[server] Booting...') this.Context = Context this.router = router - echo.info('[server] Booting...') + this.server = createServer((req, res) => { + this.requestListener(req, res).catch((e) => echo.error(e)) + }) } async start(entry: string = '') { @@ -21,13 +25,7 @@ export class CoaApplication { const port = parseInt(process.env.HOST || '') || 8000 // 启动服务 - const server = createServer( - async (req, res) => - await this.requestListener(req, res).catch((e) => { - echo.error(e) - }) - ) - server.listen(port, () => { + this.server.listen(port, () => { echo.info(`[server] Startup successful in: ${Number(process.hrtime.bigint() - this.startAt) / 1e6} ms`) echo.info(`[server] Listening on: http://localhost:${port}${entry}`) }) diff --git a/lib/service/CoaHttp.ts b/lib/service/CoaHttp.ts index c387615..c58cfbd 100644 --- a/lib/service/CoaHttp.ts +++ b/lib/service/CoaHttp.ts @@ -32,6 +32,8 @@ export class CoaHttp { // 启动应用 await this.application.start(this.config.baseUrl + 'doc') + + return { server: this.application.server } } // 注册路由