'use strict'; const db = require('../config').database; const { domain, name } = require('../config').server; const { objectMapper, pick } = require('../utils/commons.util'); const initModels = require('../models/init-models'); const Sequelize = db.sequelize; const models = initModels(Sequelize); const OutboundModelModel = models.outbound_messages; const getOutboundMessage = async msg => { const r = await OutboundModelModel.findOne({ where: msg, }); return r; }; /** * MySQL - Implemented with ON DUPLICATE KEY UPDATE */ const upsertOutboundMessage = async (key, data) => { const defaultR = { direction: 'outbound' }; const r1 = pick(data, ['actionId', 'msgtype', 'externalId', 'id']); 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, sn: key, message_origin: JSON.stringify(data) }; const [instance, created] = await OutboundModelModel.upsert({ ...toUpsert }, { returning: true }); console.info('upsertOutboundMessage', { instance, created }); return instance.toJSON(); }; module.exports = { getOutboundMessage, upsertOutboundMessage };