env-plugin 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Container.js +20 -1
- package/dist/PostProxyServer.js +37 -12
- package/dist/client/assets/element-plus-BN_JcO6B.js +19 -0
- package/dist/client/assets/element-plus-SrDBYmqw.css +1 -0
- package/dist/client/assets/index-CcOgzo-G.js +1 -0
- package/dist/client/assets/index-DcxBCPsx.css +1 -0
- package/dist/client/index.html +4 -4
- package/dist/controllers/DevServerController.js +10 -2
- package/dist/controllers/EnvController.js +43 -3
- package/dist/controllers/ImportExportController.js +44 -0
- package/dist/controllers/PasswordController.js +1 -0
- package/dist/controllers/RequestLogController.js +34 -0
- package/dist/controllers/RouteRuleController.js +1 -0
- package/dist/controllers/SystemSettingController.js +43 -0
- package/dist/index.js +13 -11
- package/dist/models/EnvModel.js +31 -3
- package/dist/repositories/DevServerRepo.js +14 -69
- package/dist/repositories/EnvRepo.js +30 -95
- package/dist/repositories/PasswordRepo.js +44 -106
- package/dist/repositories/RouteRuleRepo.js +26 -79
- package/dist/repositories/SystemSettingRepo.js +21 -0
- package/dist/repositories/database.js +11 -84
- package/dist/repositories/migrate.js +198 -0
- package/dist/repositories/store.js +118 -0
- package/dist/routes/index.js +197 -29
- package/dist/service/DevServerService.js +4 -2
- package/dist/service/EnvService.js +67 -7
- package/dist/service/ImportExportService.js +337 -0
- package/dist/service/PasswordService.js +11 -9
- package/dist/service/PreProxyServer.js +158 -36
- package/dist/service/ProxyAutoStarterService.js +3 -0
- package/dist/service/RequestLogService.js +77 -0
- package/dist/service/RouteRuleService.js +18 -16
- package/dist/service/SystemSettingService.js +90 -0
- package/dist/types/index.js +3 -0
- package/dist/types/shared/EnvItem.js +8 -0
- package/dist/types/shared/ImportExport.js +55 -0
- package/dist/types/shared/RequestLog.js +28 -0
- package/dist/types/shared/SystemSetting.js +18 -0
- package/dist/utils/ResolveConfig.js +4 -2
- package/dist/utils/asyncHandler.js +12 -0
- package/dist/utils/errors.js +2 -0
- package/dist/utils/resourceType.js +42 -0
- package/dist/utils/routeBuilder.js +19 -0
- package/package.json +36 -29
- package/templates/inject/envm-switcher.js +1418 -0
- package/dist/client/assets/element-plus-4FTV-s7u.js.gz +0 -0
- package/dist/client/assets/index-C2AH0x8U.css.gz +0 -0
- package/dist/client/assets/index-Db97pusF.js.gz +0 -0
- package/dist/client/assets/vue-CRjr1oeH.js.gz +0 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { AppError } from "../utils/errors.js";
|
|
2
|
+
export const TABLES = {
|
|
3
|
+
envms: {
|
|
4
|
+
name: "envms",
|
|
5
|
+
columns: ["id", "apiBaseUrl", "name", "port", "status", "devServerId", "sortOrder"],
|
|
6
|
+
integerColumns: ["port", "sortOrder"],
|
|
7
|
+
unique: ["apiBaseUrl"],
|
|
8
|
+
indexes: [["devServerId"]],
|
|
9
|
+
},
|
|
10
|
+
devServer: {
|
|
11
|
+
name: "devServer",
|
|
12
|
+
columns: ["id", "devServerUrl", "name", "sortOrder"],
|
|
13
|
+
integerColumns: ["sortOrder"],
|
|
14
|
+
unique: ["devServerUrl"],
|
|
15
|
+
indexes: [],
|
|
16
|
+
},
|
|
17
|
+
routeRules: {
|
|
18
|
+
name: "routeRules",
|
|
19
|
+
columns: ["id", "envId", "pathPrefix", "targetEnvId", "enabled"],
|
|
20
|
+
integerColumns: ["enabled"],
|
|
21
|
+
unique: [],
|
|
22
|
+
indexes: [["envId"], ["envId", "pathPrefix"]],
|
|
23
|
+
},
|
|
24
|
+
passwords: {
|
|
25
|
+
name: "passwords",
|
|
26
|
+
columns: ["id", "envId", "name", "isDefault"],
|
|
27
|
+
integerColumns: ["isDefault"],
|
|
28
|
+
unique: [],
|
|
29
|
+
indexes: [["envId"], ["envId", "isDefault"]],
|
|
30
|
+
},
|
|
31
|
+
settings: {
|
|
32
|
+
name: "settings",
|
|
33
|
+
columns: ["id"],
|
|
34
|
+
integerColumns: [],
|
|
35
|
+
unique: [],
|
|
36
|
+
indexes: [],
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
export function buildSchemaSql() {
|
|
40
|
+
const parts = [];
|
|
41
|
+
for (const t of Object.values(TABLES)) {
|
|
42
|
+
const cols = t.columns.map((c) => c === "id" ? "id TEXT PRIMARY KEY" : `${c} ${t.integerColumns.includes(c) ? "INTEGER" : "TEXT"}`);
|
|
43
|
+
cols.push("data TEXT NOT NULL");
|
|
44
|
+
const constraints = t.unique.length ? `, UNIQUE(${t.unique.join(", ")})` : "";
|
|
45
|
+
parts.push(`CREATE TABLE IF NOT EXISTS ${t.name} (${cols.join(", ")}${constraints});`);
|
|
46
|
+
for (const idx of t.indexes) {
|
|
47
|
+
parts.push(`CREATE INDEX IF NOT EXISTS idx_${t.name}_${idx.join("_")} ON ${t.name}(${idx.join(", ")});`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return parts.join("\n");
|
|
51
|
+
}
|
|
52
|
+
export function toSqlValue(v) {
|
|
53
|
+
if (v === undefined)
|
|
54
|
+
return null;
|
|
55
|
+
if (typeof v === "boolean")
|
|
56
|
+
return v ? 1 : 0;
|
|
57
|
+
if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "bigint" || v instanceof Uint8Array) {
|
|
58
|
+
return v;
|
|
59
|
+
}
|
|
60
|
+
return JSON.stringify(v);
|
|
61
|
+
}
|
|
62
|
+
export function serialize(table, model) {
|
|
63
|
+
const out = {};
|
|
64
|
+
for (const col of table.columns)
|
|
65
|
+
out[col] = toSqlValue(model[col]);
|
|
66
|
+
out.data = JSON.stringify(model);
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
export function insertRow(db, table, model) {
|
|
70
|
+
const s = serialize(table, model);
|
|
71
|
+
const cols = [...table.columns, "data"];
|
|
72
|
+
const sql = `INSERT INTO ${table.name} (${cols.join(", ")}) VALUES (${cols.map(() => "?").join(", ")})`;
|
|
73
|
+
db.prepare(sql).run(...cols.map((c) => s[c]));
|
|
74
|
+
}
|
|
75
|
+
export function mergeUpdate(db, table, id, patch) {
|
|
76
|
+
const row = db.prepare(`SELECT data FROM ${table.name} WHERE id = ?`).get(id);
|
|
77
|
+
if (!row)
|
|
78
|
+
return null;
|
|
79
|
+
const model = { ...JSON.parse(row.data), ...patch };
|
|
80
|
+
const s = serialize(table, model);
|
|
81
|
+
const cols = [...table.columns, "data"];
|
|
82
|
+
const sql = `UPDATE ${table.name} SET ${cols.map((c) => `${c} = ?`).join(", ")} WHERE id = ?`;
|
|
83
|
+
db.prepare(sql).run(...cols.map((c) => s[c]), id);
|
|
84
|
+
return model;
|
|
85
|
+
}
|
|
86
|
+
export function buildWhere(query, knownColumns) {
|
|
87
|
+
const clauses = [];
|
|
88
|
+
const params = [];
|
|
89
|
+
for (const [key, value] of Object.entries(query)) {
|
|
90
|
+
if (key.startsWith("$")) {
|
|
91
|
+
throw new AppError(`buildWhere 不支持顶层操作符 "${key}",请改用扁平查询或显式 SQL`);
|
|
92
|
+
}
|
|
93
|
+
const col = knownColumns.includes(key) ? key : `json_extract(data, '$.${key}')`;
|
|
94
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
95
|
+
const opKeys = Object.keys(value).filter((k) => k.startsWith("$"));
|
|
96
|
+
const unsupported = opKeys.filter((k) => k !== "$ne");
|
|
97
|
+
if (unsupported.length) {
|
|
98
|
+
throw new AppError(`buildWhere 不支持操作符 ${unsupported.join(", ")}`);
|
|
99
|
+
}
|
|
100
|
+
if (opKeys.includes("$ne")) {
|
|
101
|
+
clauses.push(`${col} != ?`);
|
|
102
|
+
params.push(toSqlValue(value.$ne));
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
clauses.push(`${col} = ?`);
|
|
107
|
+
params.push(toSqlValue(value));
|
|
108
|
+
}
|
|
109
|
+
return { where: clauses.length ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
110
|
+
}
|
|
111
|
+
export function parseData(row) {
|
|
112
|
+
if (!row)
|
|
113
|
+
return null;
|
|
114
|
+
return JSON.parse(row.data);
|
|
115
|
+
}
|
|
116
|
+
export function parseDataAll(rows) {
|
|
117
|
+
return rows.map((r) => JSON.parse(r.data));
|
|
118
|
+
}
|
package/dist/routes/index.js
CHANGED
|
@@ -1,46 +1,209 @@
|
|
|
1
1
|
// routes/index.ts
|
|
2
2
|
import express, { Router } from "express";
|
|
3
3
|
import * as libCookie from "cookie";
|
|
4
|
+
import { z } from "zod";
|
|
4
5
|
import { Container } from "../Container.js";
|
|
5
6
|
import { getConfig } from "../utils/ResolveConfig.js";
|
|
6
7
|
import { toDTO } from "../middleware/dto.middleware.js";
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
import { asyncHandler } from "../utils/asyncHandler.js";
|
|
9
|
+
import { registerRoutes } from "../utils/routeBuilder.js";
|
|
10
|
+
import { EnvPrimarySchema, EnvCreateSchema, EnvUpdateSchema, EnvSortSchema, EnvSwitchSchema, DevServerCreateSchema, DevServerDeleteSchema, DevServerUpdateSchema, DevServerSortSchema, RouteRuleCreateSchema, RouteRuleDeleteSchema, RouteRuleUpdateSchema, PasswordCreateSchema, PasswordDeleteSchema, PasswordUpdateSchema, ExportRequestSchema, ImportRequestSchema, SystemSettingUpdateSchema, } from "../types/index.js";
|
|
11
|
+
// 辅助函数:绑定 Controller 方法,确保 this 指向正确
|
|
12
|
+
const bind = (obj, method) =>
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
14
|
+
obj[method].bind(obj);
|
|
15
|
+
// 1. 创建各模块路由(声明式 RouteDefinition 配置)
|
|
16
|
+
const createEnvRoutes = (controller, importExportController) => {
|
|
10
17
|
const router = Router();
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
const routes = [
|
|
19
|
+
{
|
|
20
|
+
method: "get",
|
|
21
|
+
path: "/getlist",
|
|
22
|
+
handler: bind(controller, "handleGetList"),
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
method: "post",
|
|
26
|
+
path: "/add",
|
|
27
|
+
middleware: [toDTO(EnvCreateSchema)],
|
|
28
|
+
handler: bind(controller, "handleAddEnv"),
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
method: "post",
|
|
32
|
+
path: "/delete",
|
|
33
|
+
middleware: [toDTO(EnvPrimarySchema)],
|
|
34
|
+
handler: asyncHandler(bind(controller, "handleDeleteEnv")),
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
method: "post",
|
|
38
|
+
path: "/update",
|
|
39
|
+
middleware: [toDTO(EnvUpdateSchema)],
|
|
40
|
+
handler: bind(controller, "handleUpdateEnv"),
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
method: "post",
|
|
44
|
+
path: "/start",
|
|
45
|
+
middleware: [toDTO(EnvPrimarySchema)],
|
|
46
|
+
handler: asyncHandler(bind(controller, "handleStartServer")),
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
method: "post",
|
|
50
|
+
path: "/stop",
|
|
51
|
+
middleware: [toDTO(EnvPrimarySchema)],
|
|
52
|
+
handler: asyncHandler(bind(controller, "handleStopServer")),
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
method: "post",
|
|
56
|
+
path: "/switch",
|
|
57
|
+
middleware: [toDTO(EnvSwitchSchema)],
|
|
58
|
+
handler: asyncHandler(bind(controller, "handleSwitchEnv")),
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
method: "post",
|
|
62
|
+
path: "/proxy/switch",
|
|
63
|
+
middleware: [toDTO(z.object({ envId: z.string(), devServerId: z.string() }))],
|
|
64
|
+
handler: bind(controller, "handleSwitchProxy"),
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
method: "put",
|
|
68
|
+
path: "/sort",
|
|
69
|
+
middleware: [toDTO(EnvSortSchema)],
|
|
70
|
+
handler: bind(controller, "handleUpdateSortOrder"),
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
method: "post",
|
|
74
|
+
path: "/export",
|
|
75
|
+
middleware: [toDTO(ExportRequestSchema)],
|
|
76
|
+
handler: bind(importExportController, "handleExport"),
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
method: "post",
|
|
80
|
+
path: "/import",
|
|
81
|
+
middleware: [toDTO(ImportRequestSchema)],
|
|
82
|
+
handler: bind(importExportController, "handleImport"),
|
|
83
|
+
},
|
|
84
|
+
];
|
|
85
|
+
return registerRoutes(router, routes);
|
|
19
86
|
};
|
|
20
87
|
const createDevServerRoutes = (controller) => {
|
|
21
88
|
const router = Router();
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
89
|
+
const routes = [
|
|
90
|
+
{
|
|
91
|
+
method: "get",
|
|
92
|
+
path: "/list",
|
|
93
|
+
handler: bind(controller, "handleGetDevServerList"),
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
method: "post",
|
|
97
|
+
path: "/add",
|
|
98
|
+
middleware: [toDTO(DevServerCreateSchema)],
|
|
99
|
+
handler: bind(controller, "handleCreateDevServer"),
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
method: "put",
|
|
103
|
+
path: "/update",
|
|
104
|
+
middleware: [toDTO(DevServerUpdateSchema)],
|
|
105
|
+
handler: bind(controller, "handleUpdateDevServer"),
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
method: "put",
|
|
109
|
+
path: "/sort",
|
|
110
|
+
middleware: [toDTO(DevServerSortSchema)],
|
|
111
|
+
handler: bind(controller, "handleUpdateSortOrder"),
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
method: "delete",
|
|
115
|
+
path: "/",
|
|
116
|
+
middleware: [toDTO(DevServerDeleteSchema)],
|
|
117
|
+
handler: bind(controller, "handleDeleteDevServer"),
|
|
118
|
+
},
|
|
119
|
+
];
|
|
120
|
+
return registerRoutes(router, routes);
|
|
28
121
|
};
|
|
29
122
|
const createRouteRuleRoutes = (controller) => {
|
|
30
123
|
const router = Router();
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
124
|
+
const routes = [
|
|
125
|
+
{
|
|
126
|
+
method: "get",
|
|
127
|
+
path: "/list/:envId",
|
|
128
|
+
handler: bind(controller, "handleGetList"),
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
method: "post",
|
|
132
|
+
path: "/add",
|
|
133
|
+
middleware: [toDTO(RouteRuleCreateSchema)],
|
|
134
|
+
handler: bind(controller, "handleAdd"),
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
method: "post",
|
|
138
|
+
path: "/update",
|
|
139
|
+
middleware: [toDTO(RouteRuleUpdateSchema)],
|
|
140
|
+
handler: bind(controller, "handleUpdate"),
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
method: "post",
|
|
144
|
+
path: "/delete",
|
|
145
|
+
middleware: [toDTO(RouteRuleDeleteSchema)],
|
|
146
|
+
handler: bind(controller, "handleDelete"),
|
|
147
|
+
},
|
|
148
|
+
];
|
|
149
|
+
return registerRoutes(router, routes);
|
|
36
150
|
};
|
|
37
151
|
const createPasswordRoutes = (controller) => {
|
|
38
152
|
const router = Router();
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
153
|
+
const routes = [
|
|
154
|
+
{
|
|
155
|
+
method: "get",
|
|
156
|
+
path: "/list/:envId",
|
|
157
|
+
handler: bind(controller, "handleGetList"),
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
method: "post",
|
|
161
|
+
path: "/add",
|
|
162
|
+
middleware: [toDTO(PasswordCreateSchema)],
|
|
163
|
+
handler: bind(controller, "handleAdd"),
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
method: "post",
|
|
167
|
+
path: "/update",
|
|
168
|
+
middleware: [toDTO(PasswordUpdateSchema)],
|
|
169
|
+
handler: bind(controller, "handleUpdate"),
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
method: "post",
|
|
173
|
+
path: "/delete",
|
|
174
|
+
middleware: [toDTO(PasswordDeleteSchema)],
|
|
175
|
+
handler: bind(controller, "handleDelete"),
|
|
176
|
+
},
|
|
177
|
+
];
|
|
178
|
+
return registerRoutes(router, routes);
|
|
179
|
+
};
|
|
180
|
+
const createRequestLogRoutes = (controller) => {
|
|
181
|
+
const router = Router();
|
|
182
|
+
const routes = [
|
|
183
|
+
{
|
|
184
|
+
method: "get",
|
|
185
|
+
path: "/list",
|
|
186
|
+
handler: bind(controller, "handleGetLogs"),
|
|
187
|
+
},
|
|
188
|
+
];
|
|
189
|
+
return registerRoutes(router, routes);
|
|
190
|
+
};
|
|
191
|
+
const createSystemSettingRoutes = (controller) => {
|
|
192
|
+
const router = Router();
|
|
193
|
+
const routes = [
|
|
194
|
+
{
|
|
195
|
+
method: "get",
|
|
196
|
+
path: "/",
|
|
197
|
+
handler: bind(controller, "handleGet"),
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
method: "post",
|
|
201
|
+
path: "/",
|
|
202
|
+
middleware: [toDTO(SystemSettingUpdateSchema)],
|
|
203
|
+
handler: bind(controller, "handleUpdate"),
|
|
204
|
+
},
|
|
205
|
+
];
|
|
206
|
+
return registerRoutes(router, routes);
|
|
44
207
|
};
|
|
45
208
|
const createCommonRoutes = () => {
|
|
46
209
|
const router = Router();
|
|
@@ -48,7 +211,7 @@ const createCommonRoutes = () => {
|
|
|
48
211
|
router.get("/clear-proxy-cookie", (req, res) => {
|
|
49
212
|
const cookies = req.headers.cookie;
|
|
50
213
|
if (cookies) {
|
|
51
|
-
const cookieArr = libCookie.
|
|
214
|
+
const cookieArr = libCookie.parseCookie(cookies);
|
|
52
215
|
Object.keys(cookieArr).forEach((cookieName) => {
|
|
53
216
|
if (cookieName.endsWith(getConfig().cookieSuffix)) {
|
|
54
217
|
res.setHeader("Set-Cookie", `${cookieName}=; max-age=0; path=/`);
|
|
@@ -70,11 +233,16 @@ export const createRouter = () => {
|
|
|
70
233
|
const devServerController = container.get("devServerController");
|
|
71
234
|
const routeRuleController = container.get("routeRuleController");
|
|
72
235
|
const passwordController = container.get("passwordController");
|
|
236
|
+
const requestLogController = container.get("requestLogController");
|
|
237
|
+
const importExportController = container.get("importExportController");
|
|
238
|
+
const systemSettingController = container.get("systemSettingController");
|
|
73
239
|
// 挂载模块路由
|
|
74
|
-
rootRouter.use("/env", createEnvRoutes(envController));
|
|
240
|
+
rootRouter.use("/env", createEnvRoutes(envController, importExportController));
|
|
75
241
|
rootRouter.use("/server", createDevServerRoutes(devServerController));
|
|
76
242
|
rootRouter.use("/route-rule", createRouteRuleRoutes(routeRuleController));
|
|
77
243
|
rootRouter.use("/password", createPasswordRoutes(passwordController));
|
|
244
|
+
rootRouter.use("/request-log", createRequestLogRoutes(requestLogController));
|
|
245
|
+
rootRouter.use("/system-setting", createSystemSettingRoutes(systemSettingController));
|
|
78
246
|
rootRouter.use("/", createCommonRoutes());
|
|
79
247
|
return rootRouter;
|
|
80
248
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { DevServerQuerySchema, } from "../types/index.js";
|
|
3
3
|
import { AppError } from "../utils/errors.js";
|
|
4
4
|
import { devServerLogger } from "../utils/logger.js";
|
|
@@ -8,6 +8,8 @@ import { devServerLogger } from "../utils/logger.js";
|
|
|
8
8
|
* 依赖开发服务器仓库(DevServerRepo)和环境仓库(EnvRepo)实现数据持久化与关联业务处理
|
|
9
9
|
*/
|
|
10
10
|
class DevServerService {
|
|
11
|
+
devServerRepo;
|
|
12
|
+
envRepo;
|
|
11
13
|
/**
|
|
12
14
|
* 构造函数 - 通过依赖注入初始化仓库实例
|
|
13
15
|
* @param devServerRepo - 开发服务器仓库实例,用于devServer数据的持久化操作
|
|
@@ -36,7 +38,7 @@ class DevServerService {
|
|
|
36
38
|
// 生成唯一ID并组装完整服务器信息(默认状态为未关联)
|
|
37
39
|
const newDevServer = {
|
|
38
40
|
...validData,
|
|
39
|
-
id:
|
|
41
|
+
id: randomUUID(),
|
|
40
42
|
sortOrder: 0,
|
|
41
43
|
};
|
|
42
44
|
// 保存开发服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
2
|
import PreProxyServer from "./PreProxyServer.js";
|
|
3
3
|
import { AppError } from "../utils/errors.js";
|
|
4
4
|
import { envLogger } from "../utils/logger.js";
|
|
@@ -9,6 +9,10 @@ import * as os from "os";
|
|
|
9
9
|
* 依赖环境仓库(EnvRepo)和开发服务器仓库(DevServerRepo)实现数据持久化和关联操作
|
|
10
10
|
*/
|
|
11
11
|
class EnvService {
|
|
12
|
+
envRepo;
|
|
13
|
+
devServerRepo;
|
|
14
|
+
routeRuleRepo;
|
|
15
|
+
serverIp;
|
|
12
16
|
/**
|
|
13
17
|
* 构造函数 - 通过依赖注入初始化仓库实例
|
|
14
18
|
* @param envRepo - 环境仓库实例,用于环境数据的持久化操作
|
|
@@ -40,7 +44,7 @@ class EnvService {
|
|
|
40
44
|
// 生成唯一ID并组装完整环境信息
|
|
41
45
|
const newEnvItem = {
|
|
42
46
|
...envItem,
|
|
43
|
-
id:
|
|
47
|
+
id: randomUUID(),
|
|
44
48
|
status: "stopped", // 默认初始状态为停止
|
|
45
49
|
};
|
|
46
50
|
// 保存环境
|
|
@@ -174,11 +178,9 @@ class EnvService {
|
|
|
174
178
|
async stopServerAtSamePort(envItem) {
|
|
175
179
|
// 先查与当前服务同端口的环境,如果启动,则关闭掉
|
|
176
180
|
const samePortAndRunningEnv = this.envRepo.findOne({
|
|
177
|
-
$
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
{ status: "running" }, // 直接匹配等于的值
|
|
181
|
-
],
|
|
181
|
+
id: { $ne: envItem.id },
|
|
182
|
+
port: envItem.port,
|
|
183
|
+
status: "running",
|
|
182
184
|
});
|
|
183
185
|
if (samePortAndRunningEnv) {
|
|
184
186
|
envLogger.info({
|
|
@@ -232,6 +234,64 @@ class EnvService {
|
|
|
232
234
|
envLogger.info({ env, updatedEnv }, `环境【${env.id}】状态已更新为${updatedEnv.status}`);
|
|
233
235
|
return updatedEnv;
|
|
234
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* 环境切换:启动目标环境(不停止当前环境,允许多环境并行运行)
|
|
239
|
+
* @param currentEnvId - 当前环境ID(仅用于日志和幂等判断)
|
|
240
|
+
* @param targetEnvId - 目标环境ID
|
|
241
|
+
* @returns 目标环境信息(含端口号),供客户端重定向
|
|
242
|
+
* @throws {AppError} 当环境不存在或操作失败时抛出
|
|
243
|
+
*/
|
|
244
|
+
async handleSwitchEnv(currentEnvId, targetEnvId) {
|
|
245
|
+
envLogger.info({ currentEnvId, targetEnvId }, "准备切换环境");
|
|
246
|
+
// 检查目标环境是否存在
|
|
247
|
+
const targetEnv = this.envRepo.findOneById(targetEnvId);
|
|
248
|
+
if (!targetEnv) {
|
|
249
|
+
throw new AppError(`切换失败,目标环境【${targetEnvId}】不存在`);
|
|
250
|
+
}
|
|
251
|
+
// 如果切换到同一个环境且已在运行,则无需操作
|
|
252
|
+
if (currentEnvId === targetEnvId && targetEnv.status === "running") {
|
|
253
|
+
envLogger.info("切换到相同环境且已在运行,无需操作");
|
|
254
|
+
return targetEnv;
|
|
255
|
+
}
|
|
256
|
+
// 启动目标环境(如果已在运行则重启以确保状态正确)
|
|
257
|
+
if (targetEnv.status === "running") {
|
|
258
|
+
await this.handleStopServer({ id: targetEnvId });
|
|
259
|
+
}
|
|
260
|
+
await this.handleStartServer({ id: targetEnvId });
|
|
261
|
+
// 3. 返回目标环境最新信息
|
|
262
|
+
const updatedTarget = this.envRepo.findOneById(targetEnvId);
|
|
263
|
+
if (!updatedTarget) {
|
|
264
|
+
throw new AppError("切换后无法获取目标环境信息");
|
|
265
|
+
}
|
|
266
|
+
envLogger.info({ updatedTarget }, "环境切换成功");
|
|
267
|
+
return updatedTarget;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* 切换当前环境的 DevServer 绑定
|
|
271
|
+
* 更新 devServerId 后,PreProxyServer 在下个请求中动态读取,即时生效
|
|
272
|
+
* @param envId - 当前环境ID
|
|
273
|
+
* @param devServerId - 目标 DevServer ID
|
|
274
|
+
* @returns 更新后的环境信息
|
|
275
|
+
* @throws {AppError} 当环境或 DevServer 不存在时抛出
|
|
276
|
+
*/
|
|
277
|
+
handleSwitchProxy(envId, devServerId) {
|
|
278
|
+
envLogger.info({ envId, devServerId }, "准备切换环境代理目标");
|
|
279
|
+
// 校验环境存在
|
|
280
|
+
const env = this.envRepo.findOneById(envId);
|
|
281
|
+
if (!env) {
|
|
282
|
+
throw new AppError(`切换代理失败,环境【${envId}】不存在`);
|
|
283
|
+
}
|
|
284
|
+
// 校验 DevServer 存在
|
|
285
|
+
const devServer = this.devServerRepo.findOneById({ id: devServerId });
|
|
286
|
+
if (!devServer) {
|
|
287
|
+
throw new AppError(`切换代理失败,DevServer【${devServerId}】不存在`);
|
|
288
|
+
}
|
|
289
|
+
// 更新 devServerId(PreProxyServer 动态读取,即时生效)
|
|
290
|
+
this.envRepo.update({ id: envId, devServerId });
|
|
291
|
+
const updatedEnv = this.envRepo.findOneById(envId);
|
|
292
|
+
envLogger.info({ updatedEnv }, "环境代理目标切换成功");
|
|
293
|
+
return updatedEnv;
|
|
294
|
+
}
|
|
235
295
|
/**
|
|
236
296
|
* 批量更新排序顺序
|
|
237
297
|
* @param sortData - 排序数据
|