165 lines
6.8 KiB
JavaScript
165 lines
6.8 KiB
JavaScript
'use strict';
|
|
const httpStatus = require('http-status');
|
|
|
|
const generateControllers = require('../../core/controllers');
|
|
const { buildContext } = require('../../core/controllers');
|
|
const notificationService = require('./notification.service');
|
|
const notificationDetailService = require('./notification_detail.service');
|
|
const userDeviceService = require('./user_device.service');
|
|
|
|
const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper');
|
|
|
|
// Module Name
|
|
const MODULE_NAME = '[notification.controller]';
|
|
const controllerOptions = { MODULE_NAME };
|
|
|
|
const extraControllers = {
|
|
sendNotification: (config) => {
|
|
return async (req, res, next) => {
|
|
config = config || {
|
|
scopes: [],
|
|
};
|
|
|
|
let receipt = undefined;
|
|
const context = buildContext(req, config);
|
|
let params = extractParamsFromRequest(req, res);
|
|
|
|
let userIds = req.body.userIds;
|
|
if (!userIds) {
|
|
return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing user Ids'), res)
|
|
}
|
|
|
|
if (!req.body.title) {
|
|
return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing message title'), res)
|
|
}
|
|
|
|
if (!req.body.message) {
|
|
return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing message content'), res)
|
|
}
|
|
|
|
try {
|
|
let getUserDevicesPromise = (userId) => userDeviceService.fetchAll({ params: { userId: userId }}, context);
|
|
let saveNotificationPromise = (notification) => notificationService.create(notification, context);
|
|
let sendNotificationsPromise = (messages) => notificationService.sendNotification(messages);
|
|
let disableUserDevicePromise = (userDevice) => userDeviceService.update({
|
|
userId: userDevice.userId,
|
|
token: userDevice.token,
|
|
}, { valid: false }, context);
|
|
|
|
const notificationRecord = {
|
|
title: req.body.title,
|
|
body: req.body.message,
|
|
ttl: req.body.ttl,
|
|
priority: req.body.priority,
|
|
data: req.body.data || req.body.userIds,
|
|
};
|
|
|
|
let buildMessagePromise = async (userDevices) => {
|
|
let message = undefined;
|
|
userDevices.rows.forEach(async function (userDevice) {
|
|
if (notificationService.isValidPushToken(userDevice.token)) {
|
|
message = {
|
|
...notificationRecord,
|
|
userId: userDevice.userId,
|
|
to: userDevice.token,
|
|
sound: 'default',
|
|
};
|
|
} else {
|
|
await disableUserDevicePromise(userDevice);
|
|
}
|
|
});
|
|
return new Promise(function(resolve) { resolve(message) });
|
|
};
|
|
|
|
let getUserDevicesList = [];
|
|
|
|
userIds.forEach(function (userId) {
|
|
getUserDevicesList.push(getUserDevicesPromise(userId));
|
|
});
|
|
|
|
receipt = await saveNotificationPromise(notificationRecord)
|
|
.then(function() {
|
|
return Promise.all(getUserDevicesList)
|
|
}).then(function(userDeviceList) {
|
|
return Promise.all(userDeviceList.map(buildMessagePromise))
|
|
}).then(sendNotificationsPromise)
|
|
|
|
|
|
} catch (error) {
|
|
return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', error, res)
|
|
} finally {
|
|
return handleResultResponse(receipt, null, null, res, httpStatus.OK);
|
|
}
|
|
}
|
|
},
|
|
|
|
updateNotificationsWithReceipts: (config) => {
|
|
return async (req, res, next) => {
|
|
config = config || {
|
|
scopes: [],
|
|
};
|
|
|
|
const context = buildContext(req, config);
|
|
let params = extractParamsFromRequest(req, res);
|
|
|
|
let getNotificationsWithoutReceipt = async () => {
|
|
let params = {
|
|
where: { }
|
|
};
|
|
return await notificationDetailService.fetchAll(params, context);
|
|
}
|
|
|
|
let receipt = await Promise.all(getUserDevicesList).then(
|
|
function (userDeviceList) {
|
|
return Promise.all(userDeviceList.map(buildMessagePromise))
|
|
})
|
|
.then(sendNotificationsPromise)
|
|
}
|
|
},
|
|
|
|
registerDevice: (config) => {
|
|
return async (req, res, next) => {
|
|
config = config || {
|
|
scopes: [],
|
|
};
|
|
|
|
try {
|
|
const context = buildContext(req, config);
|
|
var data = {
|
|
token: req.body.token,
|
|
valid: 1,
|
|
userId: context.user.id
|
|
};
|
|
|
|
let params = extractParamsFromRequest(req, res, {
|
|
includeAll: false,
|
|
paginate: { limit: 1, page: 1 },
|
|
params: {
|
|
userId: context.user.id,
|
|
token: data.token,
|
|
}
|
|
});
|
|
|
|
// Buscamos el token y el usuario
|
|
console.log('>> Busco el usuario y el token', params.params);
|
|
let result = await notificationService.fetchOne(params, context);
|
|
if (!result) {
|
|
// Dar de alta el token
|
|
console.log('>> Dar de alta el token', data);
|
|
result = await notificationService.create(data, context);
|
|
} else {
|
|
// Actualizar el token
|
|
console.log('>> Actualizar el token', params.params, data, context);
|
|
result = await notificationService.update(params.params, data, context);
|
|
}
|
|
} catch(error) {
|
|
console.error(error);
|
|
} finally {
|
|
// En todo caso devolver OK al cliente
|
|
return handleResultResponse('OK', null, null, res, httpStatus.OK);
|
|
}
|
|
}
|
|
},
|
|
};
|
|
|
|
module.exports = generateControllers(notificationService, extraControllers, controllerOptions); |