Skip to content

Commit

Permalink
refactor: router接口变更
Browse files Browse the repository at this point in the history
  • Loading branch information
linyyyang committed Jan 15, 2024
1 parent 3f11ba4 commit 401a4d2
Show file tree
Hide file tree
Showing 4 changed files with 153 additions and 102 deletions.
77 changes: 32 additions & 45 deletions src/router/grpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @Usage:
* @Author: richen
* @Date: 2021-06-29 14:10:30
* @LastEditTime: 2024-01-07 22:38:51
* @LastEditTime: 2024-01-15 22:39:07
*/
import * as Helper from "koatty_lib";
import { RouterOptions } from "./router";
Expand All @@ -12,8 +12,12 @@ import { IOCContainer } from "koatty_container";
import { ListServices, LoadProto } from "koatty_proto";
import { DefaultLogger as Logger } from "koatty_logger";
import { Handler, injectParamMetaData, injectRouter, ParamMetadata } from "./inject";
import { ServiceDefinition, UntypedHandleCall, UntypedServiceImplementation } from "@grpc/grpc-js";
import { Koatty, KoattyRouter, IRpcServerUnaryCall, IRpcServerCallback } from "koatty_core";
import { UntypedHandleCall } from "@grpc/grpc-js";
import {
Koatty, KoattyRouter, IRpcServerUnaryCall,
IRpcServerCallback, RouterImplementation
} from "koatty_core";
import { payload } from "./payload";

/**
* GrpcRouter Options
Expand All @@ -25,26 +29,6 @@ export interface GrpcRouterOptions extends RouterOptions {
protoFile: string;
}

/**
* ServiceImplementation
*
* @export
* @interface ServiceImplementation
*/
export interface ServiceImplementation {
service: ServiceDefinition;
implementation: Implementation;
}
/**
* Implementation
*
* @export
* @interface Implementation
*/
export interface Implementation {
[methodName: string]: UntypedHandleCall;
}

/**
* CtlInterface
*
Expand All @@ -66,40 +50,36 @@ interface CtlProperty {
}

export class GrpcRouter implements KoattyRouter {
app: Koatty;
readonly protocol: string;
options: GrpcRouterOptions;
router: Map<string, ServiceImplementation>;
router: Map<string, RouterImplementation>;

constructor(app: Koatty, options?: RouterOptions) {
this.app = app;
options.ext = options.ext || {};
this.options = {
...options,
protoFile: options.ext.protoFile,
};
this.router = new Map();
// payload middleware
app.use(payload(this.options.payload));
}

/**
/**
* SetRouter
*
* @param {string} name
* @param {ServiceDefinition<UntypedServiceImplementation>} service
* @param {UntypedServiceImplementation} implementation
* @returns {*}
* @memberof GrpcRouter
* @param name
* @param impl
* @returns
*/
SetRouter(name: string, service: any, implementation: UntypedServiceImplementation) {
SetRouter(name: string, impl?: RouterImplementation) {
if (Helper.isEmpty(name)) {
return;
}
const value = {
service: service,
implementation: implementation
service: impl.service,
implementation: impl.implementation
}
this.router.set(name, value);
this.app?.server?.RegisterService(value);
}

/**
Expand All @@ -108,16 +88,16 @@ export class GrpcRouter implements KoattyRouter {
* @returns {*} {Map<string, ServiceImplementation>}
* @memberof GrpcRouter
*/
ListRouter(): Map<string, ServiceImplementation> {
ListRouter(): Map<string, RouterImplementation> {
return this.router;
}

/**
* Loading router
* LoadRouter
*
* @memberof Router
*/
async LoadRouter(list: any[]) {
async LoadRouter(app: Koatty, list: any[]) {
try {
// load proto files
const pdef = LoadProto(this.options.protoFile);
Expand All @@ -127,9 +107,9 @@ export class GrpcRouter implements KoattyRouter {
for (const n of list) {
const ctlClass = IOCContainer.getClass(n, "CONTROLLER");
// inject router
const ctlRouters = injectRouter(this.app, ctlClass);
const ctlRouters = injectRouter(app, ctlClass);
// inject param
const ctlParams = injectParamMetaData(this.app, ctlClass, this.options.payload);
const ctlParams = injectParamMetaData(app, ctlClass, this.options.payload);

for (const it in ctlRouters) {
const router = ctlRouters[it];
Expand Down Expand Up @@ -161,14 +141,21 @@ export class GrpcRouter implements KoattyRouter {
const ctlItem = ctls[path];
Logger.Debug(`Register request mapping: ["${path}" => ${ctlItem.name}.${ctlItem.method}]`);
impl[handler.name] = (call: IRpcServerUnaryCall<any, any>, callback: IRpcServerCallback<any>) => {
return this.app.callback("grpc", (ctx) => {
return app.callback("grpc", (ctx) => {
const ctl = IOCContainer.getInsByClass(ctlItem.ctl, [ctx]);
return Handler(this.app, ctx, ctl, ctlItem.method, ctlItem.params);
return Handler(app, ctx, ctl, ctlItem.method, ctlItem.params);
})(call, callback);
};
}
}
this.SetRouter(serviceName, si.service, impl);
// set router
this.SetRouter(serviceName, {
service: si.service, implementation: impl
});
app?.server?.RegisterService({
service: si.service,
implementation: impl
});
}

} catch (err) {
Expand Down
85 changes: 59 additions & 26 deletions src/router/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @Usage:
* @Author: richen
* @Date: 2021-06-28 19:02:06
* @LastEditTime: 2024-01-07 22:39:54
* @LastEditTime: 2024-01-15 23:55:23
*/
import KoaRouter from "@koa/router";
import * as Helper from "koatty_lib";
Expand All @@ -13,65 +13,95 @@ import { IOCContainer } from "koatty_container";
import { DefaultLogger as Logger } from "koatty_logger";
import { Handler, injectParamMetaData, injectRouter } from "./inject";
import { RequestMethod } from "./mapping";
import { Koatty, KoattyContext, KoattyNext, KoattyRouter } from "koatty_core";
import {
Koatty, KoattyContext, KoattyRouter,
RouterImplementation
} from "koatty_core";
import { payload } from "./payload";

// HttpImplementation
export type HttpImplementation = (ctx: KoattyContext, next: KoattyNext) => Promise<any>;

/**
* HttpRouter class
*/
export class HttpRouter implements KoattyRouter {
app: Koatty;
readonly protocol: string;
options: RouterOptions;
router: KoaRouter;
private routerMap: Map<string, RouterImplementation>;

constructor(app: Koatty, options?: RouterOptions) {
this.app = app;
this.options = {
...options
};
// initialize
this.router = new KoaRouter(this.options);
this.routerMap = new Map();
// payload middleware
app.use(payload(this.options.payload));
}

/**
* Set router
*
* @param {string} path
* @param {RequestMethod} [method]
* @param name
* @param impl
* @returns
*/
SetRouter(path: string, func: HttpImplementation, method?: RequestMethod) {
if (Helper.isEmpty(method)) {
SetRouter(name: string, impl?: RouterImplementation) {
if (Helper.isEmpty(impl.path)) {
return;
}
method = method ?? RequestMethod.ALL;
this.router[method](path, func);
const method = (impl.method || "").toLowerCase();
switch (method) {
case "get":
this.router.get(impl.path, <any>impl.implementation);
break;
case "post":
this.router.post(impl.path, <any>impl.implementation);
break;
case "put":
this.router.put(impl.path, <any>impl.implementation);
break;
case "delete":
this.router.delete(impl.path, <any>impl.implementation);
break;
case "patch":
this.router.patch(impl.path, <any>impl.implementation);
break;
case "options":
this.router.options(impl.path, <any>impl.implementation);
break;
case "head":
this.router.head(impl.path, <any>impl.implementation);
break;
default:
this.router.all(impl.path, <any>impl.implementation);
break;
}
this.routerMap.set(name, impl);
}

/**
* ListRouter
*
* @returns {*} {KoaRouter.Middleware<any, unknown>}
* @returns {*} {Map<string, RouterImplementation> }
*/
ListRouter() {
return this.router.routes();
ListRouter(): Map<string, RouterImplementation> {
return this.routerMap;
}

/**
*
* LoadRouter
*
* @param {any[]} list
*/
LoadRouter(list: any[]) {
async LoadRouter(app: Koatty, list: any[]) {
try {
for (const n of list) {
const ctlClass = IOCContainer.getClass(n, "CONTROLLER");
// inject router
const ctlRouters = injectRouter(this.app, ctlClass);
const ctlRouters = injectRouter(app, ctlClass);
// inject param
const ctlParams = injectParamMetaData(this.app, ctlClass, this.options.payload);
const ctlParams = injectParamMetaData(app, ctlClass, this.options.payload);
// tslint:disable-next-line: forin
for (const it in ctlRouters) {
const router = ctlRouters[it];
Expand All @@ -80,16 +110,19 @@ export class HttpRouter implements KoattyRouter {
const requestMethod = <RequestMethod>router.requestMethod;
const params = ctlParams[method];
Logger.Debug(`Register request mapping: ["${path}" => ${n}.${method}]`);
this.SetRouter(path, (ctx: KoattyContext): Promise<any> => {
const ctl = IOCContainer.getInsByClass(ctlClass, [ctx]);
return Handler(this.app, ctx, ctl, method, params);
}, requestMethod);
this.SetRouter(path, {
path,
method: requestMethod,
implementation: (ctx: KoattyContext): Promise<any> => {
const ctl = IOCContainer.getInsByClass(ctlClass, [ctx]);
return Handler(app, ctx, ctl, method, params);
},
});
}
}

// exp: in middleware
// app.Router.SetRouter('/xxx', (ctx: Koa.KoattyContext): any => {...}, 'GET')
this.app.use(this.ListRouter()).
app.use(this.router.routes()).
use(this.router.allowedMethods());
} catch (err) {
Logger.Error(err);
Expand Down
2 changes: 1 addition & 1 deletion src/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @Usage:
* @Author: richen
* @Date: 2023-12-09 12:02:29
* @LastEditTime: 2023-12-09 23:12:34
* @LastEditTime: 2024-01-16 00:18:22
* @License: BSD (3-Clause)
* @Copyright (c): <richenlin(at)gmail.com>
*/
Expand Down
Loading

0 comments on commit 401a4d2

Please sign in to comment.