From df2d9d0ee2110b66aa6ab69f935e96b2ca16d2fb Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 25 Oct 2023 19:34:52 +0800 Subject: [PATCH] feat: add lifecyle with koa-compose --- packages/core/README.md | 10 ++++++++++ packages/core/package.json | 3 ++- packages/core/src/index.ts | 31 ++++++++++++++++++++++++++++++- 3 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 packages/core/README.md diff --git a/packages/core/README.md b/packages/core/README.md new file mode 100644 index 0000000..9efe175 --- /dev/null +++ b/packages/core/README.md @@ -0,0 +1,10 @@ + + + +## lifecyle + +- beforeAll + - beforeEach + - afterEach +- afterAll + diff --git a/packages/core/package.json b/packages/core/package.json index 445b96e..f3e9da8 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -33,6 +33,7 @@ "dependencies": { "@koa/bodyparser": "^5.0.0", "debug": "^4.3.4", - "koa": "^2.14.2" + "koa": "^2.14.2", + "koa-compose": "^4.1.0" } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 438b3f3..4f0cb8d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,6 +1,7 @@ import { bodyParser } from '@koa/bodyparser'; import debug from 'debug'; import Koa from 'koa'; +import compose from 'koa-compose'; import { mountMiddleware } from './core'; import { isArrowFunction } from './utils'; @@ -9,9 +10,35 @@ export const lib = () => 'lib'; const log = debug('httprpc'); +export const LifeCycleConfig = { + beforeAll: async (ctx, next) => { + console.log('beforeAll'); + await next(); + console.log('beforeAll end'); + }, + beforeEach: async (ctx, next) => { + console.log('beforeEach'); + await next(); + console.log('beforeEach end'); + }, + afterEach: async (ctx, next) => { + console.log('afterEach'); + await next(); + console.log('afterEach end'); + }, + afterAll: async (ctx, next) => { + console.log('afterAll'); + await next(); + console.log('afterAll end'); + }, +}; + export function httprpc(config?: any) { + const _cfg = Object.assign(LifeCycleConfig, config); const app = new Koa(); + app.use(_cfg.beforeAll); + app.use(bodyParser()); // console.log(config); @@ -24,6 +51,7 @@ export function httprpc(config?: any) { _mounted: false, listen: function (port?: number) { this.mount(); + app.use(_cfg.afterAll); this.app.listen(port || 3000); }, add: function (items) { @@ -45,7 +73,8 @@ export function httprpc(config?: any) { log('mount'); if (!this._mounted) { - app.use(mountMiddleware(this.rpcFunctions)); + const mw = compose([_cfg.beforeEach, mountMiddleware(this.rpcFunctions), _cfg.afterEach]); + app.use(mw); this._mounted = true; } },