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

77 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-01-10 11:28:39 +00:00
const got = require('got');
2019-03-27 07:48:13 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
2020-01-15 12:27:14 +00:00
Self.remoteMethod('send', {
2019-03-27 07:48:13 +00:00
description: 'Sends SMS to a destination phone',
2019-05-23 09:39:14 +00:00
accessType: 'WRITE',
2021-07-08 13:53:30 +00:00
accepts: [
{
arg: 'destinationFk',
type: 'integer'
},
{
arg: 'destination',
type: 'string',
required: true,
},
{
arg: 'message',
type: 'string',
required: true,
}
],
2019-03-27 07:48:13 +00:00
returns: {
2021-07-08 13:53:30 +00:00
type: 'object',
2019-03-27 07:48:13 +00:00
root: true
},
http: {
path: `/send`,
verb: 'POST'
}
});
2019-04-16 05:59:12 +00:00
Self.send = async(ctx, destinationFk, destination, message) => {
2019-03-27 07:48:13 +00:00
const userId = ctx.req.accessToken.userId;
const smsConfig = await Self.app.models.SmsConfig.findOne();
const params = {
2022-01-10 12:20:57 +00:00
api_key: smsConfig.apiKey,
messages: [{
2022-01-10 14:14:05 +00:00
from: smsConfig.title,
2022-01-10 12:20:57 +00:00
to: destination,
text: message
}]
2019-03-27 07:48:13 +00:00
};
2022-01-10 14:14:05 +00:00
let response;
2019-03-27 07:48:13 +00:00
try {
2022-01-10 14:14:05 +00:00
if (process.env.NODE_ENV !== 'production')
params.fake = 1;
const jsonTest = {
json: params
};
response = await got.post(smsConfig.uri, jsonTest).json();
2019-03-27 07:48:13 +00:00
} catch (e) {
console.error(e);
}
2022-01-10 14:14:05 +00:00
const [result] = response.result;
const status = result.error_id;
2019-04-16 05:59:12 +00:00
2019-03-27 07:48:13 +00:00
const newSms = {
senderFk: userId,
2019-04-16 05:59:12 +00:00
destinationFk: destinationFk || null,
destination: destination,
2019-03-27 07:48:13 +00:00
message: message,
2022-01-10 14:14:05 +00:00
status: status
2019-03-27 07:48:13 +00:00
};
2019-04-16 05:59:12 +00:00
const sms = await Self.create(newSms);
2021-07-08 13:53:30 +00:00
2022-01-10 14:14:05 +00:00
if (status)
2019-03-27 07:48:13 +00:00
throw new UserError(`We weren't able to send this SMS`);
return sms;
};
};