Skip to content

Commit

Permalink
feat: add lifecyle with koa-compose
Browse files Browse the repository at this point in the history
  • Loading branch information
npmstudy committed Oct 25, 2023
1 parent 8b946f7 commit df2d9d0
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
10 changes: 10 additions & 0 deletions packages/core/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@



## lifecyle

- beforeAll
- beforeEach
- afterEach
- afterAll

3 changes: 2 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
31 changes: 30 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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);
Expand All @@ -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) {
Expand All @@ -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;
}
},
Expand Down

0 comments on commit df2d9d0

Please sign in to comment.