81 lines
2.2 KiB
JavaScript
81 lines
2.2 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',
|
||
|
accepts: [{
|
||
|
arg: 'recipientFk',
|
||
|
type: 'Integer'
|
||
|
},
|
||
|
{
|
||
|
arg: 'recipient',
|
||
|
type: 'String',
|
||
|
required: true,
|
||
|
},
|
||
|
{
|
||
|
arg: 'message',
|
||
|
type: 'String',
|
||
|
required: true,
|
||
|
}],
|
||
|
returns: {
|
||
|
type: 'boolean',
|
||
|
root: true
|
||
|
},
|
||
|
http: {
|
||
|
path: `/send`,
|
||
|
verb: 'POST'
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Self.send = async(ctx, recipientFk, recipient, 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: recipient,
|
||
|
msg: message
|
||
|
};
|
||
|
|
||
|
let xmlResponse;
|
||
|
let xmlResult;
|
||
|
let xmlParsed;
|
||
|
let status;
|
||
|
|
||
|
try {
|
||
|
[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 newSms = {
|
||
|
senderFk: userId,
|
||
|
destinationFk: recipientFk || null,
|
||
|
destination: recipient,
|
||
|
message: message,
|
||
|
statusCode: status.codigo,
|
||
|
status: status.descripcion
|
||
|
};
|
||
|
|
||
|
const sms = Self.create(newSms);
|
||
|
|
||
|
if (status.codigo != 200)
|
||
|
throw new UserError(`We weren't able to send this SMS`);
|
||
|
|
||
|
return sms;
|
||
|
};
|
||
|
};
|