feat: 添加middleware

This commit is contained in:
2024-08-28 22:51:07 +08:00
parent 70a363db86
commit 321a4b41e7
6 changed files with 823 additions and 755 deletions

View File

@@ -31,13 +31,14 @@ const templateFn = (codeStr: string) => {
`;
};
export const loadOne = async (item: RouterCodeModel) => {
const { path, key, id, code, exec, project } = item.toJSON();
const { path, key, id, code, exec, project, middleware } = item.toJSON();
const codeStr = exec || code;
try {
const fn: any = new Function('ctx', templateFn(codeStr));
// run code
const codeRunRoute = new Route(path, key, { id });
codeRunRoute.run = fn;
codeRunRoute.middleware = middleware;
router.removeById(id); // TODO:
router.add(codeRunRoute);
return {
@@ -64,7 +65,7 @@ export const loadOne = async (item: RouterCodeModel) => {
export const load = async function () {
const codes = await RouterCodeModel.findAll();
const codeManager: CodeManager[] = codes.map((item) => {
const { path, key, id, code, exec, project, active } = item.toJSON();
const { path, key, id, code, exec, project, active, middleware } = item.toJSON();
if (!active) {
return {
...item.toJSON(),
@@ -73,6 +74,7 @@ export const load = async function () {
id,
code,
project,
middleware,
status: CodeStatus.stop,
};
}
@@ -82,6 +84,7 @@ export const load = async function () {
// run code
const codeRunRoute = new Route(path, key, { id });
codeRunRoute.run = fn;
codeRunRoute.middleware = middleware;
router.add(codeRunRoute);
return {
...item.toJSON(),

View File

@@ -109,7 +109,7 @@ router.add(startRouterById);
// add or update router
export const updateRouter = new Route('admin', 'updateRouter');
updateRouter.run = async (ctx) => {
let { path, key, id, code, type = 'route' } = ctx.query;
let { path, key, id, code, middleware, type = 'route' } = ctx.query;
if (!path && !key) {
ctx.body = 'path and key is required';
ctx.code = 500;
@@ -126,6 +126,7 @@ updateRouter.run = async (ctx) => {
codeRouter.path = path;
codeRouter.key = key;
codeRouter.code = code;
codeRouter.middleware = middleware;
try {
codeRouter.exec = await transform(code);
} catch (e) {
@@ -138,7 +139,7 @@ updateRouter.run = async (ctx) => {
} else {
try {
const exec = await transform(code);
const newCodeRouter = new RouterCodeModel({ path, key, code, exec, type });
const newCodeRouter = new RouterCodeModel({ path, key, code, exec, type, middleware });
await newCodeRouter.save();
codeRouter = newCodeRouter;
} catch (e) {