79 lines
2.6 KiB
JavaScript
79 lines
2.6 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
|
||
/**
|
||
* 仓库开放 API — 站内信模块处理器。
|
||
* 接收仓库级外部适配器推送的 inbox.push 请求,
|
||
* 统一委托 app/service/inbox/receiver.receive 处理写库与异步推送。
|
||
*/
|
||
class WarehouseInboxService extends MainService {
|
||
/**
|
||
* 仓库 API 消息入站入口。
|
||
* warehouse_id 从验签后上下文注入,禁止外部传入。
|
||
* @param {Object} options 请求参数。
|
||
* @param {Object} options.body 请求体。
|
||
* @return {Promise<Object>} 入站结果。
|
||
*/
|
||
async push({ body = {} } = {}) {
|
||
const { ctx } = this;
|
||
const { warehouseId, appKey } = this.getInfo();
|
||
|
||
// 安全边界:warehouse_id 一律从验签后上下文获取
|
||
if (!warehouseId) {
|
||
throw new Error('缺少仓库信息');
|
||
}
|
||
|
||
// 安全边界:校验必填参数
|
||
if (!body.requestId || !String(body.requestId).trim()) {
|
||
throw new Error('requestId 不能为空');
|
||
}
|
||
|
||
// 构造 ext_id
|
||
const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`;
|
||
|
||
// 解析消息原始发送时间(可选,用于历史消息过滤)
|
||
const sendTime = this.parseSendTime(body.sendTime);
|
||
|
||
// 构造入站数据并委托给 inbox receiver
|
||
const result = await ctx.service.inbox.receiver.receive({
|
||
ext_id: extId,
|
||
warehouse_id: warehouseId,
|
||
direction: 'inbound',
|
||
parent_id: body.parentId || null,
|
||
source_type: 'api',
|
||
source_extra: String(appKey || ''),
|
||
target_type: body.targetType || 'im',
|
||
group_name: body.groupName || null,
|
||
user_name: body.userName || null,
|
||
group_id: body.groupId || null,
|
||
user_id: body.userId || null,
|
||
content: body.content || null,
|
||
ext_data: body.extData || null,
|
||
flags: body.flags || {},
|
||
send_time: sendTime,
|
||
});
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 解析外部传入的消息发送时间。
|
||
* 支持毫秒时间戳、秒时间戳、ISO 时间字符串;解析失败返回 null。
|
||
* @param {number|string|null} value 外部传入的 sendTime。
|
||
* @return {number|null} 毫秒时间戳,解析失败返回 null。
|
||
*/
|
||
parseSendTime(value) {
|
||
if (value == null || value === '') return null;
|
||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||
if (value > 1e12) return Math.floor(value); // 毫秒
|
||
if (value > 1e8) return Math.floor(value * 1000); // 秒
|
||
return null;
|
||
}
|
||
const ms = Date.parse(String(value));
|
||
return Number.isFinite(ms) ? ms : null;
|
||
}
|
||
}
|
||
|
||
module.exports = WarehouseInboxService;
|