feat: add admin router manager

This commit is contained in:
xion
2024-06-25 00:52:43 +08:00
parent f8777bd4ea
commit 3454e39ea4
18 changed files with 831 additions and 368 deletions

View File

@@ -0,0 +1 @@
export { manager } from './manager.ts';

View File

@@ -0,0 +1,57 @@
import { router } from '../../modules/router.ts';
import { Route } from '@abearxiong/router';
import { RouterCodeModel, RouterCode } from '../../models/code.ts';
enum CodeStatus {
success = 0,
fail = 1,
}
export type CodeManager = {
fn?: any;
status?: CodeStatus;
errorMsg?: string;
} & Partial<RouterCode>;
const codeDemoRun = `async function run(ctx) {
ctx.body = 'test js';
return ctx;
}`;
export const load = async function () {
const codes = await RouterCodeModel.findAll();
const codeManager: CodeManager[] = codes.map((item) => {
const { path, key, id, code, project } = item.toJSON();
console.log('item', item, 'code', item.code);
try {
const fn: any = new Function(
'ctx',
`
${code}
return run(ctx);
`,
);
// run code
const codeRunRoute = new Route(path, key, { id });
codeRunRoute.run = fn;
router.add(codeRunRoute);
return {
path,
key,
id,
project,
fn,
status: CodeStatus.success,
};
} catch (e) {
console.error('error id:', id, '\n', e);
return {
path,
key,
id,
project,
status: CodeStatus.fail,
errorMsg: e.message.toString(),
};
}
});
return codeManager;
};

View File

@@ -0,0 +1,33 @@
import { EventEmitter, once } from 'stream';
import { load, CodeManager } from './load.ts';
export enum LoadStatus {
LOADING = 'loading',
LOADED = 'loaded',
ERROR = 'error',
}
export const manager = {
loaded: LoadStatus.LOADING, // 是否已经加载
list: [] as CodeManager[],
};
export const events = new EventEmitter();
once(events, 'loaded')
.then(() => {
manager.loaded = LoadStatus.LOADED;
console.log('manager loaded');
})
.catch((e) => {
manager.loaded = LoadStatus.ERROR;
console.error('manager loaded error', e);
});
const init = async function () {
const r = await load();
manager.list = r;
events.emit('loaded');
};
init();