Skip to content

Commit

Permalink
chore: refact
Browse files Browse the repository at this point in the history
  • Loading branch information
npmstudy committed Nov 6, 2023
1 parent 618c5bc commit d3854d3
Show file tree
Hide file tree
Showing 22 changed files with 104 additions and 1,590 deletions.
5 changes: 0 additions & 5 deletions example/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@ import mount from '@tomrpc/mount';
(async () => {
const rpc = createServer({
base: import.meta.url,
beforeOne: function (ctx: any, key: string) {
console.log(ctx.path);
console.log(ctx.method);
console.log('beforeOne key=' + key);
},
});

rpc.fn('getUsers', function (a: string) {
Expand Down
89 changes: 74 additions & 15 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,11 @@

```js
const rpc = createServer({
beforeOne: function (ctx: any, key: string) {
console.log(ctx.path);
console.log(ctx.method);
console.log('beforeOne key=' + key);
},
...
});

```

## lifecyle

- beforeAll(中间件)
- beforeEach(中间件)
- beforeOne(普通函数)
- 函数执行
- afterOne(普通函数)
- afterEach(中间件)
- afterAll(中间件)

## example

Expand Down Expand Up @@ -73,5 +60,77 @@ rpc.add({

// rpc.mount();

rpc.listen(3000);
rpc.start(3000);
```

## 实现插件

```ts
import { Plugable } from './src/plugin';
export default class Fn extends Plugable {
constructor(cfg?) {
super(cfg);
this.prefix = '/demo';
this.name = 'demo';
const a = this.a();

this.addInit(a);
}
process() {
return async (ctx, next) => {
console.dir('process child');
if (ctx.path === '/') {
ctx.body = { '/': 23 };
} else {
// ctx.body = { '2323api': 23 };
await next();
}
};
}
a() {
return async (ctx, next) => {
console.dir('a ' + ctx.path);
await next();
};
}
}
```

生命周期

- before:[] 可变数组
- init:[] 可变数组
- load:[] 可变数组
- mount(plugin.prefix, plugin.app) 默认行为,不可操作
- pre(可选,返回值是 Koa 中间件)
- process(可选,返回值是 Koa 中间件)
- post(可选,返回值是 Koa 中间件)
- config.hooks.default 可在server配置里覆写
- after:[] 可变数组

生命周期操作方法,在构造函数中,增加到对应的数组即可

- this.addInit(a);
- this.addLoad(b);

被mount的中间件,实际上执行的是compose([pre, process, post]);

> 在plugin构造函数里,执行了this.load.push(this.getMiddleware());
- pre(可选,返回值是Koa中间件)
- process(可选,返回值是Koa中间件)
- post(可选,返回值是Koa中间件)


## RpcServer


```js
const rpc = new RpcServer({});

const fn = new Fn({});

rpc.plugin(fn);

rpc.start(3000)
```
File renamed without changes.
File renamed without changes.
3 changes: 2 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@koa/bodyparser": "^5.0.0",
"debug": "^4.3.4",
"koa": "^2.14.2",
"koa-compose": "^4.1.0"
"koa-compose": "^4.1.0",
"koa-mount": "^4.0.0"
}
}
4 changes: 2 additions & 2 deletions packages/core/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import request from 'supertest';
import { describe, expect, it } from 'vitest';

import { lib } from '..';
// import { lib } from '..';

describe('lib', () => {
it('should render lib', () => {
expect(lib()).toBe('lib');
expect('lib').toBe('lib');
});
});

Expand Down
31 changes: 0 additions & 31 deletions packages/core/src/core.ts

This file was deleted.

File renamed without changes.
216 changes: 15 additions & 201 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,209 +1,23 @@
import { bodyParser } from '@koa/bodyparser';
import debug from 'debug';
import Koa from 'koa';
import compose from 'koa-compose';
import { Fn } from './fn';
import { RpcServer } from './server';
export * from './plugin';
export * from './fn';
export * from './server';
export * from './utils';

import { mountMiddleware } from './core';
import { isArrowFunction, getHttpMethods } from './utils';
export function createServer(cfg?: any) {
const rpc = new RpcServer(Object.assign({ fn: {} }, cfg));

export const lib = () => 'lib';
const fn = new Fn(Object.assign({}, cfg.fn));

const log = debug('@tomrpc/core');
rpc.plugin(fn);

export const LifeCycleConfig = {
hooks: {
init: [],
before: [],
load: [],
beforeMount: [],
afterMount: [],
after: [],
},
init: async (server) => {
const app = server.app;
const loadMiddlewares = server.config.hooks.init;
console.log(loadMiddlewares);
loadMiddlewares.forEach((mw) => {
app.use(mw);
});
},
before: async (server) => {
const app = server.app;
const loadMiddlewares = server.config.hooks.before;
loadMiddlewares.forEach((mw) => {
app.use(mw);
});
},
load: async (server) => {
const app = server.app;
const loadMiddlewares = server.config.hooks.load;
console.log(loadMiddlewares);
loadMiddlewares.forEach((mw) => {
app.use(mw);
});
},
after: async (server) => {
const app = server.app;
const loadMiddlewares = server.config.hooks.after;
loadMiddlewares.forEach((mw) => {
app.use(mw);
});
},
beforeMount: async (server) => {
const app = server.app;
const loadMiddlewares = server.config.hooks.beforeMount;
loadMiddlewares.forEach((mw) => {
app.use(mw);
});
},
afterMount: async (server) => {
const app = server.app;
const loadMiddlewares = server.config.hooks.afterMount;
loadMiddlewares.forEach((mw) => {
app.use(mw);
});
},
beforeAll: async (ctx, next) => {
log('beforeAll');
await next();
log('beforeAll end');
},
beforeEach: async (ctx, next) => {
log('beforeEach');
await next();
log('beforeEach end');
},
afterEach: async (ctx, next) => {
log('afterEach');
await next();
log('afterEach end');
},
afterAll: async (ctx, next) => {
log('afterAll');
await next();
log('afterAll end');
},
beforeOne: function (ctx, key: string) {
log('beforeOne key=' + key);
},
afterOne: function (ctx, key: string) {
log('afterOne key=' + key);
},
};

export const createServer = function (config?: any) {
const _cfg = Object.assign(LifeCycleConfig, config);

// 在app时用
this.config = _cfg;
this.base = _cfg.base;

const app = new Koa();
app.use(bodyParser());

this.app = app;
this.use = app.use;

//
app.use(_cfg.beforeAll);

_cfg.before(this);

return Object.assign(this, {
rpcFunctions: {},
_mounted: false,
listen: function (port?: number) {
_cfg.init(this);

_cfg.load(this);

_cfg.beforeMount(this);
this.mount();
_cfg.afterMount(this);
_cfg.after(this);
app.use(_cfg.afterAll);

this.app.listen(port || 3000);
return Object.assign(rpc, {
fn: function (key, fun) {
fn.fn(key, fun);
},
add: function (items) {
for (const [name, fn] of Object.entries(items)) {
if (isArrowFunction(fn)) {
console.log(
`this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this`
);
}
if (this.rpcFunctions[name]) {
log(`add ${name}: ${fn}`);
console.log(`this.rpcFunctions[${name}] exisit`);
}

this.rpcFunctions[name] = fn;
}
},
mount: function () {
log('mount');

if (!this._mounted) {
const mw = compose([
_cfg.beforeEach,
async (ctx, next) => {
log('beforeOne');
const key = ctx.path.replace('/', '').split('/').join('.');
_cfg.beforeOne(ctx, key);

const lastKey = key.split('.').pop();
const httpMethods = getHttpMethods();

const supportMethods = [];
httpMethods.forEach(function (m) {
if (lastKey.indexOf(m) != -1) {
log(m);
supportMethods.push(m);
return m;
}
});
// console.log(supportMethods);

if (supportMethods.length === 0) {
log('没有匹配到包含get/post等方法的函数');
await next();
} else if (ctx.method === supportMethods[0]) {
log('匹配到包含get/post等方法的函数');
await next();
} else {
log('匹配到包含get/post等方法的函数,但method不对');
ctx.body =
'process fn:' +
lastKey +
' , you need send ' +
supportMethods[0] +
' request from client';
}

log('beforeOne end');
},
mountMiddleware(this.rpcFunctions),
async (ctx, next) => {
log('afterOne');
const key = ctx.path.replace('/', '').split('/').join('.');
_cfg.afterOne(ctx, key);
await next();
log('afterOne end');
},
_cfg.afterEach,
]);
app.use(mw);
this._mounted = true;
}
},
dump: function (): void {
for (const [name, fn] of Object.entries(this.rpcFunctions)) {
console.log(`${name}: ${fn}`);
}
},

fn: function (name: string, fn: any) {
this.rpcFunctions[name] = fn;
fn.add(items);
},
});
};
}
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit d3854d3

Please sign in to comment.