'use strict'; const { Controller } = require('egg'); const { FIELD_TYPE_LIST, listGroupDefs, listFieldDefs, normalizeFieldValues, } = require('../lib/warehouseApiFields'); /** * @controller WarehouseApiFieldController 仓库接口配置项 * 配置项定义(分组 + 字段清单 + 类型)硬编码在 app/lib/warehouseApiFields.js; * 配置项值由本组接口整体覆盖读写,落库在 warehouse_apis.extra */ class WarehouseApiFieldController extends Controller { /** * @summary 配置项定义(硬编码分组、字段清单与类型枚举) * @description 前端按 group 分组渲染小标题、按 type 渲染对应的表单控件;不需要传主体 * @router get /api/warehouse-api-fields * @apikey * @response 200 warehouseApiFieldSchemaResponse success */ async index() { const { ctx } = this; ctx.body = { code: 0, message: 'success', data: { types: FIELD_TYPE_LIST, groups: listGroupDefs(), fields: listFieldDefs(), }, }; } /** * @summary 查询某个接口配置的配置项值 * @description 统一走模型 getFieldValues() 读取,返回 { 字段名: 值 } JSON 对象,未配置的字段返回硬编码默认值 * @router get /api/warehouse-apis/{id}/fields * @apikey * @request path integer *id 接口配置主键ID * @response 200 warehouseApiFieldValuesResponse success */ async show() { const { ctx } = this; const item = await this.findApi(ctx.params.id); if (!item) return; ctx.body = { code: 0, message: 'success', data: { api_id: Number(item.id), values: item.getFieldValues() }, }; } /** * @summary 保存某个接口配置的配置项值 * @description 按字段类型校验后整体覆盖保存;字段 key 需在硬编码清单内 * @router put /api/warehouse-apis/{id}/fields * @apikey * @request path integer *id 接口配置主键ID * @request body updateWarehouseApiFieldValuesRequest *body * @response 200 baseResponse success */ async update() { const { ctx } = this; const item = await this.findApi(ctx.params.id); if (!item) return; const { values, errors } = normalizeFieldValues(ctx.request.body.values); if (errors.length) { ctx.status = 400; ctx.body = { code: 400, message: errors.join(';') }; return; } await item.update({ extra: values }); ctx.body = { code: 0, message: 'success', data: { api_id: Number(item.id) } }; } /** * 按主键取接口配置,不存在时写 404 响应 * @param {String|Number} id 接口配置主键 * @return {Object|null} 接口配置实例 */ async findApi(id) { const { ctx } = this; const item = await ctx.model.WarehouseApi.findByPk(id); if (!item) { ctx.status = 404; ctx.body = { code: 404, message: '接口配置不存在' }; return null; } return item; } } module.exports = WarehouseApiFieldController;