salix/modules/client/back/methods/sms/send.js

93 lines
2.6 KiB
JavaScript

const soap = require('soap');
const xmlParser = require('xml2js').parseString;
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('send', {
description: 'Sends SMS to a destination phone',
accessType: 'WRITE',
accepts: [{
arg: 'destinationFk',
type: 'Integer'
},
{
arg: 'destination',
type: 'String',
required: true,
},
{
arg: 'message',
type: 'String',
required: true,
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/send`,
verb: 'POST'
}
});
Self.send = async(ctx, destinationFk, destination, message) => {
const userId = ctx.req.accessToken.userId;
const smsConfig = await Self.app.models.SmsConfig.findOne();
const soapClient = await soap.createClientAsync(smsConfig.uri);
const params = {
user: smsConfig.user,
pass: smsConfig.password,
src: smsConfig.title,
dst: destination,
msg: message
};
let xmlResponse;
let xmlResult;
let xmlParsed;
let status;
try {
if (process.env.NODE_ENV !== 'production') {
status = {
codigo: [200],
descripcion: ['Fake response']
};
} else {
[xmlResponse] = await soapClient.sendSMSAsync(params);
xmlResult = xmlResponse.result.$value;
xmlParsed = await new Promise((resolve, reject) => {
xmlParser(xmlResult, (err, result) => {
if (err)
reject(err);
resolve(result);
});
});
[status] = xmlParsed['xtratelecom-sms-response'].sms;
}
} catch (e) {
console.error(e);
}
const statusCode = status.codigo[0];
const statusDescription = status.descripcion[0];
const newSms = {
senderFk: userId,
destinationFk: destinationFk || null,
destination: destination,
message: message,
statusCode: statusCode,
status: statusDescription
};
const sms = await Self.create(newSms);
if (statusCode != 200)
throw new UserError(`We weren't able to send this SMS`);
return sms;
};
};