You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Global-sales/wai-server/api/messages/message.controller.js

49 lines
2.0 KiB
JavaScript

'use strict';
const generateId = require('../../utils/generateId.util');
const { sessionStore } = require('../../core');
const { objectMapper, pick } = require('../../utils/commons.util');
const { upsertOutboundMessage } = require('../../services/outbound_messages.service');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
exports.sendText = async ctx => {
const { from, to, msgcontent, content: _content, actionId } = ctx.request.body;
const content = _content || msgcontent.body || '';
if (!from || !content) {
ctx.assert(from, 400, 'From and message are required');
return;
}
const wsToSend = sessionStore.getSession(from);
// console.log('find wsToSend', wsToSend)
if (!wsToSend) {
ctx.assert(wsToSend, 400, 'Session not found'); // 404
return;
}
try {
return wsToSend.sendTextMessage(to, content).then(({ messageId }) => {
// const messageId = generateId();
const _data = ctx.request.body;
const defaultR = { direction: 'outbound' };
const r1 = pick(_data, ['actionId', 'msgtype', 'externalId']);
r1.id = messageId;
r1.wamid = messageId;
r1.msg_status = 'accepted';
r1.createTime = Date.now();
const record = objectMapper(_data, { from: 'froms', to: 'tos' }, false);
const byType = _data.msgtype === 'text' ? { text_body: _data.msgcontent.body, text_preview_url: _data.msgcontent.preview_url } : {};
const toUpsert = { ...defaultR, ...r1, ...record, ...byType, message_origin: JSON.stringify(_data) };
upsertOutboundMessage(null, { ...toUpsert });
return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
});
// const sockMsg = await wsToSend.sendTextMessage(to, content, actionId);
// return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
} catch (error) {
console.error('Error sending message:', error);
ctx.assert(null, 500, 'Failed to send message');
}
};