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

76 lines
1.9 KiB
JavaScript

const got = require('got');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('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 params = {
'api_key': smsConfig.apiKey,
'mensage': [
{
'from': '693474205',
'to': destination,
'text': message
}
]
};
try {
if (process.env.NODE_ENV !== 'production')
params.fake = 1;
const response = got.post(smsConfig.uri, params);
} catch (e) {
console.error(e);
}
const statusCode = response.status;
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;
};
};