feat: 设置默认的context

This commit is contained in:
xion 2024-11-12 11:19:11 +08:00
parent 303c579e92
commit 780d744a16
3 changed files with 9 additions and 5 deletions

View File

@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package",
"name": "@kevisual/router",
"version": "0.0.4-alpha-7",
"version": "0.0.4-alpha-8",
"description": "",
"main": "dist/index.js",
"module": "dist/index.js",

View File

@ -26,7 +26,7 @@ export class App<T = {}> {
const router = opts?.router || new QueryRouter();
const server = opts?.server || new Server(opts?.serverOptions || {});
server.setHandle(router.getHandle(router, opts?.routerHandle, opts?.routerContext));
router.setContext(opts?.routerContext);
this.router = router;
this.server = server;
if (opts?.io) {
@ -81,7 +81,7 @@ export class App<T = {}> {
}
async call(message: { path: string; key: string; payload?: any }, ctx?: RouteContext & { [key: string]: any }) {
const router = this.router;
return await router.parse(message, ctx);
return await router.call(message, ctx);
}
exportRoutes() {
return this.router.exportRoutes();
@ -97,4 +97,3 @@ export class App<T = {}> {
throw new CustomError(...args);
}
}

View File

@ -262,6 +262,7 @@ export class Route {
export class QueryRouter {
routes: Route[];
maxNextRoute = 40;
context?: RouteContext = {}; // default context for call
constructor() {
this.routes = [];
}
@ -479,7 +480,10 @@ export class QueryRouter {
return await this.runRoute(path, key, ctx);
}
async call(message: { path: string; key: string; payload?: any }, ctx?: RouteContext & { [key: string]: any }) {
return await this.parse(message, ctx);
return await this.parse(message, { ...this.context, ...ctx });
}
async setContext(ctx: RouteContext) {
this.context = ctx;
}
getList(): RouteInfo[] {
return this.routes.map((r) => {
@ -534,6 +538,7 @@ export class QueryRouterServer extends QueryRouter {
constructor(opts?: QueryRouterServerOpts) {
super();
this.handle = this.getHandle(this, opts?.handleFn, opts?.context);
this.setContext(opts?.context);
}
setHandle(wrapperFn?: HandleFn, ctx?: RouteContext) {
this.handle = this.getHandle(this, wrapperFn, ctx);