92 lines
2.6 KiB
JavaScript
92 lines
2.6 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, options) => {
|
|
if (!recipientId) return false;
|
|
|
|
let tx;
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
|
|
const models = Self.app.models;
|
|
const userId = ctx.req.accessToken.userId;
|
|
const sender = await models.Account.findById(userId);
|
|
const recipient = await models.Account.findById(recipientId, null, myOptions);
|
|
|
|
// 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}`);
|
|
|
|
const chat = await models.Chat.create({
|
|
senderFk: sender.id,
|
|
recipient: `@${recipient.name}`,
|
|
dated: Date.vnNew(),
|
|
checkUserStatus: 1,
|
|
message: message,
|
|
status: 'sending',
|
|
attempts: 0
|
|
}, myOptions);
|
|
|
|
try {
|
|
await Self.sendCheckingUserStatus(chat);
|
|
await updateChat(chat, 'sent', myOptions);
|
|
} catch (error) {
|
|
await updateChat(chat, 'error', error, myOptions);
|
|
}
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
return true;
|
|
};
|
|
|
|
/**
|
|
* Update status and attempts of a chat
|
|
*
|
|
* @param {object} chat - The chat
|
|
* @param {string} status - The new status
|
|
* @param {string} error - The error
|
|
* @param {object} options - Query options
|
|
* @return {Promise} - The request promise
|
|
*/
|
|
|
|
async function updateChat(chat, status, error, options) {
|
|
return chat.updateAttributes({
|
|
status: status,
|
|
attempts: ++chat.attempts,
|
|
error: error
|
|
}, options);
|
|
}
|
|
};
|