'use strict'; const { Controller } = require('egg'); /** 路径参数转正整数,非法返回 null */ function toId(value) { const id = Number(value); return Number.isInteger(id) && id > 0 ? id : null; } /** * 运维/内部:用户 CRUD(能看/改**所有**账号,所以挂在 `middleware.internalAuth()` 后面) * * 面向:运维脚本、后台系统。前端 SPA 用的是 `/api/web/*`(只能动自己的东西)。 */ class InternalUserController extends Controller { /** GET /api/users?page=1&pageSize=20&keyword=&status= */ async index() { const { ctx } = this; const { page, pageSize, keyword, status } = ctx.query; const data = await ctx.service.user.list({ page, pageSize, keyword, status }); ctx.body = { ok: true, data }; } /** GET /api/users/:id —— 走 Redis 缓存,未命中回源数据库 */ async show() { const { ctx } = this; const id = toId(ctx.params.id); if (!id) { ctx.status = 400; ctx.body = { ok: false, message: 'id 必须是正整数' }; return; } const user = await ctx.service.cache.remember( `user:${id}`, ctx.app.config.cache.ttl, () => ctx.service.user.findById(id), ); if (!user) { ctx.status = 404; ctx.body = { ok: false, message: '用户不存在' }; return; } ctx.body = { ok: true, data: user }; } /** POST /api/users */ async create() { const { ctx } = this; const body = ctx.request.body || {}; if (!body.nickname) { ctx.status = 422; ctx.body = { ok: false, message: 'nickname 不能为空' }; return; } const user = await ctx.service.user.create(body); ctx.status = 201; ctx.body = { ok: true, data: user }; } /** PUT /api/users/:id */ async update() { const { ctx } = this; const id = toId(ctx.params.id); if (!id) { ctx.status = 400; ctx.body = { ok: false, message: 'id 必须是正整数' }; return; } const user = await ctx.service.user.update(id, ctx.request.body || {}); if (!user) { ctx.status = 404; ctx.body = { ok: false, message: '用户不存在' }; return; } // 数据变更后让缓存失效 await ctx.service.cache.del(`user:${id}`); ctx.body = { ok: true, data: user }; } /** DELETE /api/users/: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.user.remove(id); if (!removed) { ctx.status = 404; ctx.body = { ok: false, message: '用户不存在' }; return; } await ctx.service.cache.del(`user:${id}`); ctx.body = { ok: true, data: { id } }; } } module.exports = InternalUserController;