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.
76 lines
2.5 KiB
JavaScript
76 lines
2.5 KiB
JavaScript
const generateId = require('../../utils/generateId.util');
|
|
const whatsappEvents = require('../emitter');
|
|
const { callWebhook } = require('../webhook');
|
|
const { addConnection, updateConnection } = require('../../services/connections.service');
|
|
const { objectMapper } = require('../../utils/commons.util');
|
|
|
|
const logger = console;
|
|
|
|
const connectionEventNames = ['connection:added', 'connection:updated', 'connection:removed'];
|
|
const messageEventNames = ['message:received', 'message:updated'];
|
|
|
|
const eeventTypeMapped = {
|
|
'message:received': 'wai.message.received',
|
|
'message:updated': 'wai.message.updated',
|
|
};
|
|
|
|
const webhookBodyBuilder = (messageData, messageType) => {
|
|
const message = {
|
|
id: `evt_${generateId().replace(/-/g, '')}`,
|
|
type: eeventTypeMapped[messageType],
|
|
apiVersion: 'v2',
|
|
webhooksource: 'wai',
|
|
createTime: new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString(), // GMT +8
|
|
waiMessage: messageData,
|
|
};
|
|
return message;
|
|
};
|
|
|
|
const setupConnectionHandler = () => {
|
|
// connectionEventNames.forEach(eventName => {
|
|
logger.info(`Setting up event ${'connection:added'}`);
|
|
whatsappEvents.on('connection:added', async connectionData => {
|
|
try {
|
|
await addConnection({
|
|
...objectMapper(connectionData, { phone: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id', createTimestamp: 'createtime' }),
|
|
service_type: 'baileys',
|
|
status: 'connecting',
|
|
});
|
|
} catch (error) {
|
|
logger.error({ connectionData, error }, 'error add connection');
|
|
}
|
|
});
|
|
whatsappEvents.on('connection:updated', async connectionData => {
|
|
try {
|
|
await updateConnection({
|
|
...objectMapper(connectionData, { phone: [{ key: 'wa_id' }, { key: 'sesson_id' }], channelId: 'channel_id' }),
|
|
service_type: 'baileys',
|
|
});
|
|
} catch (error) {
|
|
logger.error({ connectionData, error }, 'error add connection');
|
|
}
|
|
});
|
|
// });
|
|
};
|
|
|
|
const setupMessageHandler = () => {
|
|
messageEventNames.forEach(eventName => {
|
|
logger.info(`Setting up event ${eventName}`);
|
|
whatsappEvents.on(eventName, async messageData => {
|
|
try {
|
|
const x = webhookBodyBuilder(messageData, eventName);
|
|
await callWebhook(x);
|
|
} catch (error) {
|
|
logger.error({ messageData, error }, 'error call webhook');
|
|
}
|
|
});
|
|
});
|
|
};
|
|
|
|
function setupWhatsappHandler() {
|
|
setupConnectionHandler();
|
|
setupMessageHandler();
|
|
}
|
|
|
|
module.exports = { setupWhatsappHandler };
|