68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import { Query } from '@kevisual/query/query';
|
|
import { QueryRouterServer, Route } from '@kevisual/router/src/route.ts';
|
|
export class QueryProxy {
|
|
query: Query;
|
|
router: QueryRouterServer;
|
|
token?: string;
|
|
constructor(opts?: { query: Query, router?: QueryRouterServer, token?: string }) {
|
|
this.query = opts?.query || new Query();
|
|
this.router = opts?.router || new QueryRouterServer();
|
|
this.token = opts?.token;
|
|
}
|
|
/**
|
|
* 初始化路由
|
|
* @returns
|
|
*/
|
|
async init() {
|
|
const that = this;
|
|
const res = await this.query.post<{ list: RouterItem[] }>({ path: "router", key: 'list', token: this.token });
|
|
if (res.code !== 200) {
|
|
console.error('Failed to init query proxy router:', res.message);
|
|
return
|
|
}
|
|
const _list = res.data?.list || []
|
|
for (const item of _list) {
|
|
if (item.path && item.key) {
|
|
console.log(`Register route: [${item.path}] ${item.key}`);
|
|
this.router.route({
|
|
path: item.path,
|
|
key: item.key,
|
|
description: item.description,
|
|
metadata: item.metadata,
|
|
}).define(async (ctx) => {
|
|
const msg = { ...ctx.query };
|
|
if (msg.token === undefined && that.token !== undefined) {
|
|
msg.token = that.token;
|
|
}
|
|
const r = await that.query.post<any>({ path: item.path, key: item.key, ...msg });
|
|
ctx.forward(r)
|
|
}).addTo(that.router);
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* 列出路由
|
|
* @param filter
|
|
* @returns
|
|
*/
|
|
async listRoutes(filter?: (item: Route) => boolean) {
|
|
return this.router.routes.filter(filter || (() => true));
|
|
}
|
|
/**
|
|
* 运行路由
|
|
* @param msg
|
|
* @returns
|
|
*/
|
|
async run(msg: { id?: string, path?: string, key?: string }) {
|
|
return await this.router.run(msg);
|
|
}
|
|
}
|
|
|
|
type RouterItem = {
|
|
id?: string;
|
|
path?: string;
|
|
key?: string;
|
|
description?: string;
|
|
middleware?: string[];
|
|
metadata?: Record<string, any>;
|
|
} |