salix/back/methods/sms/send.js

57 lines
1.6 KiB
JavaScript

const got = require('got');
const isProduction = require('vn-loopback/server/boot/isProduction');
const {models} = require('vn-loopback/server/server');
module.exports = Self => {
Self.send = async(senderFk, destination, message, options) => {
const smsConfig = await models.SmsConfig.findOne();
const [{prefix: spainPrefix}] = await Self.rawSql(
'SELECT prefix FROM pbx.prefix WHERE country = ?', ['es'], options
);
if (destination.length == 9)
destination = spainPrefix + destination;
const params = {
api_key: smsConfig.apiKey,
messages: [{
from: smsConfig.title,
to: destination,
text: message
}]
};
let response;
try {
if (!isProduction(false))
response = {result: [{status: 'ok'}]};
else {
const body = {
json: params
};
response = await got.post(smsConfig.uri, body).json();
}
} catch (e) {
console.error(e);
}
if (!options?.insert) return;
const [result] = response.result;
const error = result.error_id;
if (senderFk) senderFk = senderFk.req.accessToken.userId;
const newSms = {
senderFk,
destination: destination,
message: message,
status: error
};
const sms = await Self.create(newSms);
if (error)
throw new UserError(`We weren't able to send this SMS`);
return sms;
};
};