| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257 |
- import { Hono } from "hono";
- import debug from "debug";
- import type {
- DeviceType,
- } from "../client/share/monitorTypes.ts";
- import {
- EnableStatus,
- DeleteStatus,
- } from "../client/share/types.ts";
- import type { Variables, WithAuth } from "./middlewares.ts";
- const log = {
- api: debug("d8d:device:api"),
- };
- // 创建设备类型路由
- export function createDeviceTypesRoutes(withAuth: WithAuth) {
- const deviceTypesRoutes = new Hono<{ Variables: Variables }>();
- // 获取设备类型列表
- deviceTypesRoutes.get("/", withAuth, async (c) => {
- try {
- const apiClient = c.get('apiClient');
- // 获取分页参数
- const page = Number(c.req.query("page")) || 1;
- const limit = Number(c.req.query("limit")) || 10;
- const offset = (page - 1) * limit;
- // 获取筛选参数
- const name = c.req.query("name");
- const code = c.req.query("code");
- // 构建查询
- let query = apiClient.database
- .table("device_types")
- .where("is_deleted", DeleteStatus.NOT_DELETED)
- .orderBy("id", "desc");
- // 应用筛选条件
- if (name) {
- query = query.where("name", "like", `%${name}%`);
- }
- if (code) {
- query = query.where("code", "like", `%${code}%`);
- }
- // 克隆查询以获取总数
- const countQuery = query.clone();
- // 执行分页查询
- const deviceTypes = await query.limit(limit).offset(offset);
- // 获取总数
- const count = await countQuery.count();
- return c.json({
- data: deviceTypes,
- pagination: {
- total: Number(count),
- current: page,
- pageSize: limit,
- totalPages: Math.ceil(Number(count) / limit),
- },
- });
- } catch (error) {
- log.api("获取设备类型列表失败:", error);
- return c.json({ error: "获取设备类型列表失败" }, 500);
- }
- });
- // 获取单个设备类型
- deviceTypesRoutes.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 [deviceType] = await apiClient.database
- .table("device_types")
- .where({ id, is_deleted: DeleteStatus.NOT_DELETED });
- if (!deviceType) {
- return c.json({ error: "设备类型不存在" }, 404);
- }
- return c.json(deviceType);
- } catch (error) {
- log.api("获取设备类型详情失败:", error);
- return c.json({ error: "获取设备类型详情失败" }, 500);
- }
- });
- // 创建设备类型
- deviceTypesRoutes.post("/", withAuth, async (c) => {
- try {
- const data = (await c.req.json()) as Partial<DeviceType>;
- // 验证必填字段
- if (!data.name || !data.code) {
- return c.json({ error: "类型名称和编码不能为空" }, 400);
- }
- const apiClient = c.get('apiClient');
- // 检查编码是否已存在
- const existingCode = await apiClient.database
- .table("device_types")
- .where({ code: data.code, is_deleted: DeleteStatus.NOT_DELETED })
- .first();
- if (existingCode) {
- return c.json({ error: "类型编码已存在" }, 400);
- }
- // 插入新记录
- const [id] = await apiClient.database.table("device_types").insert({
- ...data,
- is_enabled: data.is_enabled ?? EnableStatus.ENABLED,
- is_deleted: DeleteStatus.NOT_DELETED,
- });
- // 获取创建的记录
- const [createdType] = await apiClient.database
- .table("device_types")
- .where("id", id);
- return c.json({
- message: "设备类型创建成功",
- data: createdType,
- });
- } catch (error) {
- log.api("创建设备类型失败:", error);
- return c.json({ error: "创建设备类型失败" }, 500);
- }
- });
- // 更新设备类型
- deviceTypesRoutes.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<DeviceType>;
- // 验证必填字段
- if (!data.name || !data.code) {
- return c.json({ error: "类型名称和编码不能为空" }, 400);
- }
- const apiClient = c.get('apiClient');
- // 检查编码是否已存在(且不是当前记录)
- if (data.code) {
- const existingCode = await apiClient.database
- .table("device_types")
- .where({ code: data.code, is_deleted: DeleteStatus.NOT_DELETED })
- .whereNot("id", id.toString())
- .first();
- if (existingCode) {
- return c.json({ error: "类型编码已存在" }, 400);
- }
- }
- // 检查记录是否存在
- const existingType = await apiClient.database
- .table("device_types")
- .where({ id, is_deleted: DeleteStatus.NOT_DELETED })
- .first();
- if (!existingType) {
- return c.json({ error: "设备类型不存在" }, 404);
- }
- // 更新记录
- await apiClient.database
- .table("device_types")
- .where("id", id)
- .update({
- ...data,
- updated_at: apiClient.database.fn.now(),
- });
- // 获取更新后的记录
- const [updatedType] = await apiClient.database
- .table("device_types")
- .where("id", id);
- return c.json({
- message: "设备类型更新成功",
- data: updatedType,
- });
- } catch (error) {
- log.api("更新设备类型失败:", error);
- return c.json({ error: "更新设备类型失败" }, 500);
- }
- });
- // 删除设备类型(软删除)
- deviceTypesRoutes.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 relatedInstances = await apiClient.database
- .table("device_instances")
- .where({ type_id: id, is_deleted: DeleteStatus.NOT_DELETED })
- .first();
- if (relatedInstances) {
- return c.json({ error: "该类型有关联的设备实例,无法删除" }, 400);
- }
- // 检查记录是否存在
- const existingType = await apiClient.database
- .table("device_types")
- .where({ id, is_deleted: DeleteStatus.NOT_DELETED })
- .first();
- if (!existingType) {
- return c.json({ error: "设备类型不存在" }, 404);
- }
- // 软删除
- await apiClient.database.table("device_types").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 deviceTypesRoutes;
- }
|