119 lines
3.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const apiSignLib = require('../../../lib/api_sign');
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
const DISPATCH_TIMEOUT_MS = 10000; // 10s 超时
/**
* 统一出站基类,所有渠道 dispatch 继承此类。
* 统一处理:查密钥、签名、发 HTTP。
* 子类只需实现 push(record) 方法,关注消息格式转换。
*/
class OutboundBase extends Service {
/**
* 获取仓库 ApiApp 密钥配置(IM 渠道无需签名,返回 null)。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} ApiApp 配置对象,含 appKey / selfAppSecret / warehouseId。
*/
async getApiApp(warehouseId) {
const { ctx } = this;
try {
// 通过仓库ID查找该仓库的 warehouse 类型 ApiApp
const apiApp = await ctx.model.ApiApp.findOne({
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ],
where: {
warehouse_id: warehouseId,
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
is_enabled: 1,
},
raw: true,
});
if (!apiApp || !apiApp.self_app_secret) {
return null;
}
return {
appKey: apiApp.self_app_key,
selfAppSecret: apiApp.self_app_secret,
warehouseId: Number(apiApp.warehouse_id),
};
} catch (error) {
ctx.logger.warn(`[inbox dispatch] 获取仓库 ApiApp 失败: ${error.message}`);
return null;
}
}
/**
* 生成 MD5 签名,返回带签名后的完整 URL。
* @param {string} url 原始目标URL。
* @param {*} body 请求体。
* @param {Object} secret ApiApp 密钥对象,含 appKey / selfAppSecret。
* @return {string} 带签名的完整URL。
*/
signRequest(url, body, secret) {
const timestamp = Math.floor(Date.now() / 1000);
const query = {
app_key: secret.appKey,
timestamp,
};
const { sign } = apiSignLib.signRequest({
query,
body,
selfAppSecret: secret.selfAppSecret,
});
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}app_key=${encodeURIComponent(query.app_key)}&timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
}
/**
* 统一 HTTP POST 发送。
* @param {string} url 目标URL。
* @param {*} body 请求体。
* @param {Object} [options] 额外选项。
* @param {Object} [options.headers] 自定义请求头。
* @return {Promise<{status: number, data: *}>} 响应结果。
*/
async post(url, body, options = {}) {
const { ctx } = this;
const headers = {
'Content-Type': 'application/json',
...(options.headers || {}),
};
try {
const response = await ctx.curl(url, {
method: 'POST',
dataType: 'json',
contentType: 'json',
data: body,
headers,
timeout: DISPATCH_TIMEOUT_MS,
});
return {
status: response.status,
data: response.data,
};
} catch (error) {
throw new Error(`HTTP 推送失败: ${error.message}`);
}
}
/**
* 子类必须实现的推送方法。
* @param {Object} record 消息记录(Sequelize Model 实例),子类按需使用。
* @throws {Error} 子类未实现时抛出。
*/
async push(record) {
const id = record && record.id;
throw new Error(`子类必须实现 push(record) 方法,当前消息ID: ${id || '未知'}`);
}
}
module.exports = OutboundBase;