const isProduction = require('vn-loopback/server/boot/isProduction'); 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) => { const userId = ctx.req.accessToken.userId; try { const models = Self.app.models; const sender = await models.VnUser.findById(userId, {fields: ['id']}); const error = `Could not send message from user ${userId}`; if (!recipientId) throw new Error(error); const recipient = await models.VnUser.findById(recipientId, null); if (!recipient) throw new Error(error); // Prevent sending messages to yourself if (recipientId == userId) return false; if (!isProduction()) 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; } catch (e) { await Self.rawSql(` INSERT INTO util.debug (variable, value) VALUES ('sendCheckingPresence_error', ?) `, [`User: ${userId}, recipient: ${recipientId}, message: ${message}, error: ${e}`]); } }; };