const {Email} = require('vn-print'); const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('send', { description: 'Send notifications from queue', accessType: 'WRITE', returns: { type: 'object', root: true }, http: { path: `/send`, verb: 'POST' } }); Self.send = async options => { const models = Self.app.models; const findStatus = 'pending'; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const notificationQueue = await models.NotificationQueue.find({ where: {status: findStatus}, include: [ { relation: 'notification', scope: { include: { relation: 'subscription', scope: { include: { relation: 'user', scope: { fields: ['name', 'email', 'lang'] } } } } } } ] }, myOptions); const statusSent = 'sent'; const statusError = 'error'; for (const queue of notificationQueue) { const queueName = queue.notification().name; const queueParams = JSON.parse(queue.params); for (const notificationUser of queue.notification().subscription()) { try { const sendParams = { recipient: notificationUser.user().email, lang: notificationUser.user().lang }; if (notificationUser.userFk == queue.authorFk) { await queue.updateAttribute('status', statusSent); continue; } const newParams = Object.assign({}, queueParams, sendParams); const email = new Email(queueName, newParams); if (process.env.NODE_ENV != 'test') await email.send(); await queue.updateAttribute('status', statusSent); } catch (error) { await queue.updateAttribute('status', statusError); } } } }; };