From ed5c616dbe0ae7418b27a2167ea4f9c6592f97f6 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 01:39:14 +0800 Subject: [PATCH] chore: refact --- packages/core2/app.ts | 2 +- packages/core2/src/__tests__/index.test.ts | 4 +- packages/core2/src/base.ts | 12 +- packages/core2/src/core.ts | 32 ---- packages/core2/src/fn.ts | 84 +++++--- packages/core2/src/index.ts | 213 +-------------------- packages/core2/src/server.ts | 22 ++- 7 files changed, 89 insertions(+), 280 deletions(-) delete mode 100644 packages/core2/src/core.ts diff --git a/packages/core2/app.ts b/packages/core2/app.ts index d9fa050..4889d1a 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -1,5 +1,5 @@ import Demo from './demo'; -import Fn from './src/fn'; +import { Fn } from './src/fn'; import RpcServer from './src/server'; const rpc = new RpcServer({}); diff --git a/packages/core2/src/__tests__/index.test.ts b/packages/core2/src/__tests__/index.test.ts index 70aa64c..faeed0e 100644 --- a/packages/core2/src/__tests__/index.test.ts +++ b/packages/core2/src/__tests__/index.test.ts @@ -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'); }); }); diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index 1f139a9..f375348 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -49,6 +49,10 @@ export default class Plugable implements Strategy { this.load.push(this.getMiddleware()); } + getConfig(ctx) { + return ctx[this.name]; + } + proxy() { return async (ctx, next) => { console.dir('proxy prefix=' + this.prefix); @@ -65,11 +69,11 @@ export default class Plugable implements Strategy { } getMiddleware() { - console.dir('getMiddleware'); + // console.dir('getMiddleware'); const pre = this.pre(); const process = this.process(); - const after = this.after(); - return compose([pre, process, after]); + const post = this.post(); + return compose([pre, process, post]); } pre() { @@ -79,7 +83,7 @@ export default class Plugable implements Strategy { console.dir('pre end'); }; } - after() { + post() { return async (ctx, next) => { console.dir('after'); await next(); diff --git a/packages/core2/src/core.ts b/packages/core2/src/core.ts deleted file mode 100644 index 62d8fac..0000000 --- a/packages/core2/src/core.ts +++ /dev/null @@ -1,32 +0,0 @@ -import debug from 'debug'; -const log = console.log; //debug('@tomrpc/core'); - -export function mountMiddleware(routers) { - log(routers); - return async (ctx, next) => { - log('mountMiddleware'); - const key = ctx.path.replace('/', '').split('/').join('.'); - - if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { - console.log('not match $p param, no process'); - ctx.body = 'not match $p param, no process'; - } else { - const param = ctx.method === 'POST' ? ctx.request.body : JSON.parse(ctx.query.$p); - - log(key); - log(param); - log(routers[key]); - - if (routers[key]) { - const args = [...param, ctx]; - // console.dir(args); - const result = routers[key].apply(ctx, args); - ctx.body = result; - } else { - const msg = JSON.stringify(ctx, null, 4); - ctx.body = ` not match path ${ctx.path} \n ctx = ${msg}`; - } - await next(); - } - }; -} diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index a80d246..ce0b55f 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -1,11 +1,10 @@ import debug from 'debug'; import Plugable from './base'; -import { mountMiddleware } from './core'; import { isArrowFunction, getHttpMethods } from './utils'; const log = debug('@tomrpc/core'); -export default class Fn extends Plugable { +export class Fn extends Plugable { // public name: string; constructor(cfg?: any) { @@ -15,38 +14,69 @@ export default class Fn extends Plugable { this.prefix = '/api'; } fn(key, fn) { - console.dir('=this.config='); - console.dir(this.config); + // console.dir('=this.config='); + // console.dir(this.config); if (!this.config['functions']) this.config['functions'] = {}; this.config['functions'][key] = fn; - // if (Object.entries(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; - // // } - // } else { - // this.config['functions'].push(items); - // } + } + add(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.config['functions'][name]) { + log(`add ${name}: ${fn}`); + console.log(`this.rpcFunctions[${name}] exisit`); + } + // this.rpcFunctions[name] = fn; + this.config['functions'][name] = fn; + } } process() { - console.dir("this.config['functions']"); - console.dir(this); - console.dir(this.serverConfig); - return mountMiddleware(this); + console.dir('process'); + return this.mount(); } + mount() { + return async (ctx, next) => { + const prefix = this.prefix; + const routers = this.config['functions']; + log(routers); + const path = ctx.path.replace(prefix, ''); + log('mountMiddleware' + ctx.path); + const key = '/' + path.replace('/', '').split('/').join('.'); + + if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { + console.log('not match $p param, no process'); + ctx.body = 'not match $p param, no process'; + } else { + const param = ctx.method === 'POST' ? ctx.request.body : JSON.parse(ctx.query.$p); + + log(key); + log(param); + log(routers[key]); + + if (routers[key]) { + const args = [...param, ctx]; + // console.dir(args); + const result = routers[key].apply(ctx, args); + // console.dir(result); + ctx.body = result; + } else { + const msg = JSON.stringify(ctx, null, 4); + ctx.body = ` not match path ${ctx.path} \n ctx = ${msg}`; + await next(); + } + // + } + }; + } pre() { return async (ctx, next) => { - console.log('beforeOne'); + // console.log('pre'); const key = ctx.path.replace('/', '').split('/').join('.'); // this.config.beforeOne(ctx, key); @@ -56,7 +86,7 @@ export default class Fn extends Plugable { const supportMethods = []; httpMethods.forEach(function (m) { if (lastKey.indexOf(m) != -1) { - console.log(m); + // console.log(m); supportMethods.push(m); return m; } @@ -64,7 +94,7 @@ export default class Fn extends Plugable { // console.log(supportMethods); if (supportMethods.length === 0) { - console.log('没有匹配到包含get/post等方法的函数'); + console.log(ctx.path + ',没有匹配到包含get/post等开头的函数'); await next(); } else if (ctx.method === supportMethods[0]) { log('匹配到包含get/post等方法的函数'); diff --git a/packages/core2/src/index.ts b/packages/core2/src/index.ts index 317bf99..ba3288e 100644 --- a/packages/core2/src/index.ts +++ b/packages/core2/src/index.ts @@ -1,209 +1,4 @@ -import { bodyParser } from '@koa/bodyparser'; -import debug from 'debug'; -import Koa from 'koa'; -import compose from 'koa-compose'; - -import { mountMiddleware } from './core'; -import { isArrowFunction, getHttpMethods } from './utils'; - -export const lib = () => 'lib'; - -const log = debug('@tomrpc/core'); - -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); - }, - 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; - }, - }); -}; +export * from './base'; +export * from './fn'; +export * from './server'; +export * from './utils'; diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 7e4ba26..5aa6f43 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -112,6 +112,7 @@ export default class RpcServer { public mount() { console.dir('mount'); + const cfg = {}; // setting for (const plugin of this.plugins) { plugin.server = this; @@ -122,17 +123,28 @@ export default class RpcServer { console.error('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); } console.log('mount plugin.config'); - console.log(plugin); - console.log(plugin.config); - console.log(plugin.config.bind); + // console.log(plugin); + // console.log(plugin.config); + // console.log(plugin.config.bind); for (const bindnName in plugin.config.bind) { console.dir(bindnName); - this[bindnName] = plugin.config['bind'][bindnName]; + // this[bindnName] = plugin.config['bind'][bindnName]; } this.config[plugin.name] = plugin.config; + cfg[plugin.name] = plugin; } + this.app.use(async (ctx, next) => { + // ; + for (const fn in cfg) { + // console.log('--' + fn); + ctx[fn] = cfg[fn]; + } + + await next(); + }); + // hooks for (const plugin of this.plugins) { console.dir('init stage'); @@ -158,7 +170,7 @@ export default class RpcServer { // mount app for (const plugin of this.plugins) { console.dir('mount plugin ' + plugin.prefix); - // console.dir(plugin.proxy()); + // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); this.app.use(mount(plugin.prefix, plugin.app)); }