fix: add startcode

This commit is contained in:
abearxiong 2024-06-26 21:55:23 +08:00
parent 776c1287b8
commit c0a1460ad8
3 changed files with 36 additions and 2 deletions

View File

@ -1,5 +1,6 @@
import { EventEmitter, once } from 'stream';
import { load, CodeManager, CodeStatus } from './load.ts';
import { load, CodeManager, CodeStatus, loadOne } from './load.ts';
import { RouterCodeModel } from '../../models/code.ts';
export enum LoadStatus {
LOADING = 'loading',
@ -33,6 +34,15 @@ export const stopCode = (id: string) => {
manager.list[index].status = CodeStatus.stop;
}
};
export const startCode = async (code: RouterCodeModel) => {
const index = manager.list.findIndex((item) => item.id === code.id);
if (index !== -1) {
manager.list[index] = await loadOne(code);
} else {
const codeManger = await loadOne(code);
manager.list.push(codeManger);
}
};
// 事件
export const events = new EventEmitter();

View File

@ -1,7 +1,7 @@
// admin 需要最后运行并在route中进行过滤。
import { Route } from '@abearxiong/router';
import { router } from '../modules/router.ts';
import { manager, updateNewCode, removeCode, stopCode } from './dashboard/manager.ts';
import { manager, updateNewCode, removeCode, stopCode, startCode } from './dashboard/manager.ts';
import { loadOne } from './dashboard/load.ts';
import { RouterCodeModel } from '../models/code.ts';
import { nanoid } from 'nanoid';
@ -21,6 +21,12 @@ export const removeRouter = new Route('admin', 'removeRouter');
removeRouter.run = async (ctx) => {
const { path, key } = ctx.query;
router.remove({ path, key });
const routerCode = await RouterCodeModel.findOne({ where: { path, key } });
if (routerCode) {
const id = routerCode.id;
removeCode(id);
await RouterCodeModel.destroy({ where: { id } });
}
ctx.body = 'success';
return ctx;
};
@ -52,6 +58,19 @@ stopRouterById.run = async (ctx) => {
ctx.body = 'success';
return ctx;
};
// start router by id
export const startRouterById = new Route('admin', 'startRouterById');
startRouterById.run = async (ctx) => {
const { id } = ctx.query;
const routerCode = await RouterCodeModel.findByPk(id);
if (routerCode) {
routerCode.active = true;
await routerCode.save();
startCode(routerCode);
}
ctx.body = 'success';
return ctx;
};
// add or update router
export const updateRouter = new Route('admin', 'updateRouter');
updateRouter.run = async (ctx) => {

View File

@ -9,7 +9,10 @@ export type RouterCode = {
project: string;
code: string;
type: RouterCodeType;
middleware: string[];
next: string;
};
export enum RouterCodeType {
route = 'route',
middleware = 'middleware',
@ -23,6 +26,8 @@ export class RouterCodeModel extends Model {
declare project: string;
declare code: string;
declare type: RouterCodeType;
declare middleware: string[];
declare next: string; // 如果是中间件,不存在
}
RouterCodeModel.init(
{