salix/back/methods/chat/sendCheckingPresence.js

63 lines
1.9 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('sendCheckingPresence', {
description: 'Creates a message in the chat model checking the user status',
accessType: 'WRITE',
accepts: [{
arg: 'workerId',
type: 'number',
required: true,
description: 'The recipient user id'
},
{
arg: 'message',
type: 'string',
required: true,
description: 'The message'
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/sendCheckingPresence`,
verb: 'POST'
}
});
Self.sendCheckingPresence = async(ctx, recipientId, message) => {
if (!recipientId) return false;
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const sender = await models.VnUser.findById(userId, {fields: ['id']});
const recipient = await models.VnUser.findById(recipientId, null);
// Prevent sending messages to yourself
if (recipientId == userId) return false;
if (!recipient)
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
if (process.env.NODE_ENV == 'test')
message = `[Test:Environment to user ${userId}] ` + message;
const chat = await models.Chat.create({
senderFk: sender.id,
recipient: `@${recipient.name}`,
dated: Date.vnNew(),
checkUserStatus: 1,
message: message,
status: 'sending',
attempts: 0
});
try {
await Self.sendCheckingUserStatus(chat);
await Self.updateChat(chat, 'sent');
} catch (error) {
await Self.updateChat(chat, 'error', error);
}
return true;
};
};