| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- import { Hono } from "hono";
- import debug from "debug";
- import type {
- AlertNotifyConfig,
- } from "../client/share/monitorTypes.ts";
- import {
- EnableStatus,
- DeleteStatus,
- } from "../client/share/types.ts";
- import type { Variables, WithAuth } from "./middlewares.ts";
- const log = {
- api: debug("api:monitor"),
- };
- // 告警通知配置路由
- export function createAlertNotifyConfigsRoutes(withAuth: WithAuth) {
- const alertNotifyConfigsRoutes = new Hono<{ Variables: Variables }>();
-
- // 获取告警通知配置列表
- alertNotifyConfigsRoutes.get("/", withAuth, async (c) => {
- try {
- const apiClient = c.get('apiClient');
-
- // 获取分页参数
- const page = Number(c.req.query("page")) || 1;
- const pageSize = Number(c.req.query("pageSize")) || 10;
- const offset = (page - 1) * pageSize;
-
- // 获取筛选参数
- const deviceId = c.req.query("device_id")
- ? Number(c.req.query("device_id"))
- : null;
- const alertLevel = c.req.query("alert_level")
- ? Number(c.req.query("alert_level"))
- : null;
- const notifyType = c.req.query("notify_type");
- const isEnabled = c.req.query("is_enabled")
- ? Number(c.req.query("is_enabled"))
- : null;
-
- // 构建查询
- let query = apiClient.database
- .table("alert_notify_configs")
- .where("is_deleted", DeleteStatus.NOT_DELETED)
- .orderBy("id", "desc");
-
- // 应用筛选条件
- if (deviceId) {
- query = query.where("device_id", deviceId);
- }
-
- if (alertLevel !== null) {
- query = query.where("alert_level", alertLevel);
- }
-
- if (notifyType) {
- query = query.where("notify_type", notifyType);
- }
-
- if (isEnabled !== null) {
- query = query.where("is_enabled", isEnabled);
- }
-
- // 获取总记录数
- const total = await query.clone().count();
-
- // 获取分页数据
- const data = await query.limit(pageSize).offset(offset);
-
- return c.json({
- data,
- total: Number(total),
- page,
- pageSize,
- });
- } catch (error) {
- log.api("获取告警通知配置失败:", error);
- return c.json({ error: "获取告警通知配置失败" }, 500);
- }
- });
-
- // 获取单个告警通知配置
- alertNotifyConfigsRoutes.get("/:id", withAuth, async (c) => {
- try {
- const id = Number(c.req.param("id"));
-
- if (!id || isNaN(id)) {
- return c.json({ error: "无效的通知配置ID" }, 400);
- }
-
- const apiClient = c.get('apiClient');
- const config = await apiClient.database
- .table("alert_notify_configs")
- .where("id", id)
- .where("is_deleted", DeleteStatus.NOT_DELETED)
- .first();
-
- if (!config) {
- return c.json({ error: "通知配置不存在" }, 404);
- }
-
- // 处理JSON字段
- try {
- config.notify_users = config.notify_users
- ? JSON.parse(config.notify_users)
- : [];
- } catch (parseError) {
- log.api(`解析通知用户JSON失败 (配置ID: ${config.id}):`, parseError);
- config.notify_users = [];
- }
-
- return c.json(config);
- } catch (error) {
- log.api("获取告警通知配置详情失败:", error);
- return c.json({ error: "获取告警通知配置详情失败" }, 500);
- }
- });
-
- // 创建告警通知配置
- alertNotifyConfigsRoutes.post("/", withAuth, async (c) => {
- try {
- const data = (await c.req.json()) as Partial<AlertNotifyConfig>;
-
- // 验证必填字段
- if (!data.device_id) {
- return c.json({ error: "设备ID不能为空" }, 400);
- }
-
- if (data.alert_level === undefined || data.alert_level === null) {
- return c.json({ error: "告警等级不能为空" }, 400);
- }
-
- if (!data.notify_type) {
- return c.json({ error: "通知类型不能为空" }, 400);
- }
-
- if (!data.notify_users || data.notify_users.length === 0) {
- return c.json({ error: "通知用户不能为空" }, 400);
- }
-
- const apiClient = c.get('apiClient');
-
- // 检查设备是否存在
- const device = await apiClient.database
- .table("zichan_info")
- .where("id", data.device_id)
- .where("is_deleted", DeleteStatus.NOT_DELETED)
- .first();
-
- if (!device) {
- return c.json({ error: "设备不存在" }, 404);
- }
-
- // 序列化JSON字段
- const insertData = {
- ...data,
- notify_users: JSON.stringify(data.notify_users),
- is_enabled:
- data.is_enabled !== undefined ? data.is_enabled : EnableStatus.ENABLED,
- created_at: apiClient.database.fn.now(),
- updated_at: apiClient.database.fn.now(),
- };
-
- // 插入通知配置
- const [id] = await apiClient.database
- .table("alert_notify_configs")
- .insert(insertData);
-
- // 获取插入的数据
- const [insertedConfig] = await apiClient.database
- .table("alert_notify_configs")
- .where("id", id);
-
- // 处理返回的JSON字段
- try {
- const parsedConfig = {
- ...insertedConfig,
- notify_users: insertedConfig.notify_users
- ? JSON.parse(insertedConfig.notify_users)
- : [],
- };
-
- return c.json({
- message: "告警通知配置创建成功",
- data: parsedConfig,
- });
- } catch (parseError) {
- log.api(
- `解析通知用户JSON失败 (配置ID: ${insertedConfig.id}):`,
- parseError
- );
- return c.json({
- message: "告警通知配置创建成功,但解析通知用户数据失败",
- data: {
- ...insertedConfig,
- notify_users: [],
- },
- });
- }
- } catch (error) {
- log.api("创建告警通知配置失败:", error);
- return c.json({ error: "创建告警通知配置失败" }, 500);
- }
- });
-
- // 更新告警通知配置
- alertNotifyConfigsRoutes.put("/:id", withAuth, async (c) => {
- try {
- const id = Number(c.req.param("id"));
-
- if (!id || isNaN(id)) {
- return c.json({ error: "无效的通知配置ID" }, 400);
- }
-
- const data = (await c.req.json()) as Partial<AlertNotifyConfig>;
-
- const apiClient = c.get('apiClient');
-
- // 检查通知配置是否存在
- const config = await apiClient.database
- .table("alert_notify_configs")
- .where("id", id)
- .where("is_deleted", DeleteStatus.NOT_DELETED)
- .first();
-
- if (!config) {
- return c.json({ error: "通知配置不存在" }, 404);
- }
-
- // 如果更改了设备ID,检查设备是否存在
- if (data.device_id && data.device_id !== config.device_id) {
- const device = await apiClient.database
- .table("zichan_info")
- .where("id", data.device_id)
- .where("is_deleted", DeleteStatus.NOT_DELETED)
- .first();
-
- if (!device) {
- return c.json({ error: "设备不存在" }, 404);
- }
- }
-
- // 处理JSON字段
- const updateData = { ...data };
- if (data.notify_users) {
- updateData.notify_users = JSON.stringify(data.notify_users) as any;
- }
-
- // 更新通知配置
- await apiClient.database
- .table("alert_notify_configs")
- .where("id", id)
- .update({
- ...updateData,
- updated_at: apiClient.database.fn.now(),
- });
-
- // 获取更新后的数据
- const [updatedConfig] = await apiClient.database
- .table("alert_notify_configs")
- .where("id", id);
-
- // 处理返回的JSON字段
- try {
- const parsedConfig = {
- ...updatedConfig,
- notify_users: updatedConfig.notify_users
- ? JSON.parse(updatedConfig.notify_users)
- : [],
- };
-
- return c.json({
- message: "告警通知配置更新成功",
- data: parsedConfig,
- });
- } catch (parseError) {
- log.api(
- `解析通知用户JSON失败 (配置ID: ${updatedConfig.id}):`,
- parseError
- );
- return c.json({
- message: "告警通知配置更新成功,但解析通知用户数据失败",
- data: {
- ...updatedConfig,
- notify_users: [],
- },
- });
- }
- } catch (error) {
- log.api("更新告警通知配置失败:", error);
- return c.json({ error: "更新告警通知配置失败" }, 500);
- }
- });
-
- // 删除告警通知配置
- alertNotifyConfigsRoutes.delete("/:id", withAuth, async (c) => {
- try {
- const id = Number(c.req.param("id"));
-
- if (!id || isNaN(id)) {
- return c.json({ error: "无效的通知配置ID" }, 400);
- }
-
- const apiClient = c.get('apiClient');
-
- // 检查通知配置是否存在
- const config = await apiClient.database
- .table("alert_notify_configs")
- .where("id", id)
- .where("is_deleted", DeleteStatus.NOT_DELETED)
- .first();
-
- if (!config) {
- return c.json({ error: "通知配置不存在" }, 404);
- }
-
- // 软删除通知配置
- await apiClient.database
- .table("alert_notify_configs")
- .where("id", id)
- .update({
- is_deleted: DeleteStatus.DELETED,
- updated_at: apiClient.database.fn.now(),
- });
-
- return c.json({
- message: "告警通知配置删除成功",
- id,
- });
- } catch (error) {
- log.api("删除告警通知配置失败:", error);
- return c.json({ error: "删除告警通知配置失败" }, 500);
- }
- });
-
- return alertNotifyConfigsRoutes;
- }
|