salix/back/methods/chat/sendCheckingPresence.js

65 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2024-05-21 13:11:32 +00:00
const isProduction = require('vn-loopback/server/boot/isProduction');
2020-01-20 06:33:24 +00:00
module.exports = Self => {
Self.remoteMethodCtx('sendCheckingPresence', {
2022-06-08 11:08:53 +00:00
description: 'Creates a message in the chat model checking the user status',
2020-01-20 06:33:24 +00:00
accessType: 'WRITE',
accepts: [{
2022-04-07 11:08:53 +00:00
arg: 'workerId',
type: 'number',
2020-01-20 06:33:24 +00:00
required: true,
description: 'The recipient user id'
2021-03-15 11:26:11 +00:00
},
{
2020-01-20 06:33:24 +00:00
arg: 'message',
type: 'string',
2020-01-20 06:33:24 +00:00
required: true,
description: 'The message'
}],
returns: {
type: 'object',
2020-01-20 06:33:24 +00:00
root: true
},
http: {
path: `/sendCheckingPresence`,
verb: 'POST'
}
});
2023-02-08 14:15:26 +00:00
Self.sendCheckingPresence = async(ctx, recipientId, message) => {
2020-10-21 11:25:52 +00:00
if (!recipientId) return false;
2020-01-20 06:33:24 +00:00
const models = Self.app.models;
2023-10-23 05:33:52 +00:00
const userId = ctx.req.accessToken.userId;
const sender = await models.VnUser.findById(userId, {fields: ['id']});
const recipient = await models.VnUser.findById(recipientId, null);
2020-10-21 11:25:52 +00:00
// Prevent sending messages to yourself
2023-10-23 05:33:52 +00:00
if (recipientId == userId) return false;
if (!recipient)
2023-10-23 05:33:52 +00:00
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
2024-05-21 13:11:32 +00:00
if (!isProduction())
2023-10-23 05:33:52 +00:00
message = `[Test:Environment to user ${userId}] ` + message;
2022-12-19 08:59:03 +00:00
const chat = await models.Chat.create({
senderFk: sender.id,
recipient: `@${recipient.name}`,
2023-01-16 14:18:24 +00:00
dated: Date.vnNew(),
checkUserStatus: 1,
message: message,
2023-01-04 10:23:06 +00:00
status: 'sending',
attempts: 0
});
2022-06-03 11:36:21 +00:00
2023-01-04 10:23:06 +00:00
try {
await Self.sendCheckingUserStatus(chat);
2023-02-08 14:15:26 +00:00
await Self.updateChat(chat, 'sent');
2023-01-04 10:23:06 +00:00
} catch (error) {
2023-02-08 14:15:26 +00:00
await Self.updateChat(chat, 'error', error);
2023-01-04 10:23:06 +00:00
}
2022-06-03 11:36:21 +00:00
return true;
2022-02-23 11:07:05 +00:00
};
2020-01-20 06:33:24 +00:00
};