56 lines
1.6 KiB
JavaScript
56 lines
1.6 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethodCtx('send', {
|
|
description: 'Creates a direct message in the chat model for a user or a channel',
|
|
accessType: 'WRITE',
|
|
accepts: [{
|
|
arg: 'to',
|
|
type: 'string',
|
|
required: true,
|
|
description: 'User (@) or channel (#) to send the message'
|
|
}, {
|
|
arg: 'message',
|
|
type: 'string',
|
|
required: true,
|
|
description: 'The message'
|
|
}],
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/send`,
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.send = async(ctx, to, message) => {
|
|
const models = Self.app.models;
|
|
const accessToken = ctx.req.accessToken;
|
|
const sender = await models.VnUser.findById(accessToken.userId);
|
|
const recipient = to.replace('@', '');
|
|
|
|
if (sender.name != recipient) {
|
|
const chat = await models.Chat.create({
|
|
senderFk: sender.id,
|
|
recipient: to,
|
|
dated: Date.vnNew(),
|
|
checkUserStatus: 0,
|
|
message: message,
|
|
status: 'sending',
|
|
attempts: 0
|
|
});
|
|
|
|
try {
|
|
await Self.sendMessage(chat.senderFk, chat.recipient, chat.message);
|
|
await Self.updateChat(chat, 'sent');
|
|
} catch (error) {
|
|
await Self.updateChat(chat, 'error', error);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
};
|
|
};
|