'use strict'; const Service = require('egg').Service; class OpenapiService extends Service { /** * 解析 openapi method,拆分为服务路径与动作名。 * @param {string} methodName method 名称。 * @return {{ servicePath: string, actionName: string }} 解析结果。 */ resolveOpenapiMethod(methodName = '') { const method = String(methodName || '').trim(); const parts = method.split('.').filter(Boolean); const actionName = parts.pop() || ''; const servicePath = parts.join('.'); return { servicePath, actionName, }; } /** * 根据服务路径查找 openapiMethods 下的目标服务。 * @param {string} servicePath 服务路径。 * @return {Object|null} 目标服务实例。 */ getOpenapiMethodService(servicePath = '') { const { ctx } = this; const pathSegments = String(servicePath || '').split('.').filter(Boolean); let methodService = ctx.service.openapiMethods; if (pathSegments.length === 0) { return methodService; } for (const segment of pathSegments) { methodService = methodService && methodService[segment]; } return methodService || null; } /** * 分发 openapi method 到 openapiMethods 目录。 * @param {string} methodName method 名称。 * @param {Object} body 请求体。 * @param {Object} query 请求 query。 * @return {Promise} method 执行结果。 */ async dispatchOpenapiMethod(methodName, body, query) { const { servicePath, actionName } = this.resolveOpenapiMethod(methodName); const methodService = this.getOpenapiMethodService(servicePath); if (!methodService || typeof methodService[actionName] !== 'function') { return { ok: false, httpStatus: 400, code: 400, message: `openapi method 不存在: ${methodName}`, data: null, }; } const methodResult = await methodService[actionName]({ body, query, }); return { ok: true, httpStatus: 200, code: 1, message: 'ok', data: methodResult, }; } /** * 校验 openapi 基础 query 参数,仅校验 method/v/timestamp。 * @param {Object} query 请求 query 参数。 * @return {boolean} 是否通过基础参数校验。 */ validateOpenapiParams(query) { const requiredFields = [ 'method', 'v', 'timestamp' ]; for (const field of requiredFields) { if (!query || !query[field]) { return false; } } if (typeof query.method !== 'string' || !query.method.includes('.')) { return false; } return true; } /** * 读取并解析 JSON 请求体,采用 rawBody 优先策略。 * @return {Promise} 解析后的 JSON 对象。 */ async parseJsonBody() { const { ctx } = this; let jsonData = ''; if (ctx.request.rawBody) { jsonData = ctx.request.rawBody; } else if (ctx.request.body !== undefined) { jsonData = typeof ctx.request.body === 'string' ? ctx.request.body : JSON.stringify(ctx.request.body); } else { jsonData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } jsonData = jsonData ? String(jsonData) : ''; if (!jsonData || jsonData.trim() === '') { return { ok: false, httpStatus: 400, code: 400, message: 'json数据为空', data: null, }; } try { return JSON.parse(jsonData); } catch (error) { return { ok: false, httpStatus: 400, code: 400, message: 'json数据解析错误', data: null, }; } } /** * 提取并归一化 openapi 所需的 appKey 与 sign。 * @param {Object} query 请求 query 参数。 * @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。 */ normalizeSignFields(query = {}) { const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim(); const providedSign = String(query.sign || query.signature || '').trim(); return { appKey, providedSign, }; } /** * 处理 openapi 请求并返回统一结果。 * @return {Promise} 统一结果对象。 */ async processRequest() { const { ctx } = this; const query = ctx.query || {}; if (!this.validateOpenapiParams(query)) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: method/v/timestamp', data: null, }; } const body = await this.parseJsonBody(); if (body && body.ok === false) { return body; } const { appKey, providedSign } = this.normalizeSignFields(query); if (!appKey) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: app_key', data: null, }; } const { systems: systemsService } = ctx.service; const apiSignService = systemsService.apiSign; let appConfig; try { appConfig = await apiSignService.getApiAppSecretByAppKey(appKey); } catch (error) { return { ok: false, httpStatus: 401, code: 401, message: `app_key 校验失败: ${error.message}`, data: null, }; } const verifyResult = await apiSignService.verifyRequestSignByAppKey({ appKey, query, body, providedSign, }); if (!verifyResult.ok) { return { ok: false, httpStatus: 401, code: 401, message: `签名校验失败: ${verifyResult.message}`, data: null, }; } return await this.dispatchOpenapiMethod(query.method, body, { ...query, app_key: appConfig.appKey, }); } } module.exports = OpenapiService;