'use strict'; const { Controller } = require('egg'); /** 路径参数转正整数,非法返回 null */ function toId(value) { const id = Number(value); return Number.isInteger(id) && id > 0 ? id : null; } /** * 运维/内部:设备(scanners)的绑定 / 解绑 / 列表 / 详情 / 删除 * * 面向:运维脚本、后台系统 —— 可看/可管**所有人**的设备,所以挂在 `middleware.internalAuth()` 后面。 * 前端 SPA 只能管自己的设备:`/api/web/devices*`(见 controller/web/device.js)。 * * 设备侧的部分在 `app/controller/device/`(扫码登录 `auth.js`、自检保活 `self.js`、上报 `scan.js`)。 */ class InternalDeviceController extends Controller { /** * POST /api/scanner/bind —— 把设备绑定到账号(**管理侧**接口,不是设备自己调的) * 设备自己的注册/登录全部走扫码登录:`GET /api/device/login` */ async bind() { const { ctx } = this; const body = ctx.request.body || {}; const data = await ctx.service.scanner.bind({ scannerId: toId(body.scannerId), sn: body.sn, userId: body.userId, username: body.username, }); ctx.body = { ok: true, data }; } /** POST /api/scanner/unbind —— 解绑(设备保留,仅清掉归属;设备可再扫码重新认领) */ async unbind() { const { ctx } = this; const body = ctx.request.body || {}; const data = await ctx.service.scanner.unbind({ scannerId: toId(body.scannerId), sn: body.sn, }); if (!data) { ctx.status = 404; ctx.body = { ok: false, message: '扫描器不存在' }; return; } ctx.body = { ok: true, data }; } /** GET /api/scanners?page=&pageSize=&keyword=&userId=&status= —— 设备列表 */ async index() { const { ctx } = this; const { page, pageSize, keyword, userId, status } = ctx.query; const data = await ctx.service.scanner.list({ page, pageSize, keyword, userId, status }); ctx.body = { ok: true, data }; } /** GET /api/scanners/:id —— 设备详情 */ async show() { const { ctx } = this; const id = toId(ctx.params.id); if (!id) { ctx.status = 400; ctx.body = { ok: false, message: 'id 必须是正整数' }; return; } const data = await ctx.service.scanner.findById(id); if (!data) { ctx.status = 404; ctx.body = { ok: false, message: '扫描器不存在' }; return; } ctx.body = { ok: true, data }; } /** DELETE /api/scanners/:id —— 软删除设备 */ async destroy() { const { ctx } = this; const id = toId(ctx.params.id); if (!id) { ctx.status = 400; ctx.body = { ok: false, message: 'id 必须是正整数' }; return; } const removed = await ctx.service.scanner.remove(id); if (!removed) { ctx.status = 404; ctx.body = { ok: false, message: '扫描器不存在' }; return; } ctx.body = { ok: true, data: { id } }; } } module.exports = InternalDeviceController;