-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #58 from Saca-la-Bici/feature/0.2.0/pushNotifications
Base para enviar push notifications con Firebase Cloud Messaging
- Loading branch information
Showing
7 changed files
with
169 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 25 additions & 1 deletion
26
modules/anuncios/controllers/registrarAnuncio.controller.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
const { | ||
Usuario | ||
} = require('../../../models/perfil/usuario.model'); | ||
|
||
exports.actualizarFCM = async (request, response) => { | ||
const { | ||
fcmToken | ||
} = request.body; | ||
|
||
if (!fcmToken) { | ||
return response.status(400).json({ | ||
message: 'fcmToken es requerido' | ||
}); | ||
} | ||
|
||
try { | ||
// Eliminar el token de cualquier otra cuenta que lo tenga registrado | ||
await Usuario.updateMany({ | ||
fcmTokens: fcmToken | ||
}, { | ||
$pull: { | ||
fcmTokens: fcmToken | ||
} | ||
}); | ||
|
||
// Buscar al usuario por UID | ||
const user = await Usuario.findOne({ | ||
firebaseUID: request.userUID.uid | ||
}); | ||
|
||
if (user) { | ||
// Agregar el token si no existe | ||
if (!user.fcmTokens.includes(fcmToken)) { | ||
user.fcmTokens.push(fcmToken); | ||
await user.save(); | ||
} | ||
} | ||
|
||
response.status(200).json({ | ||
message: 'Token de FCM actualizado exitosamente' | ||
}); | ||
} catch (error) { | ||
console.error('Error al actualizar el token de FCM:', error); | ||
response.status(500).json({ | ||
message: 'Error al actualizar el token de FCM' | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
|
||
const verifyToken = require('../../../util/verifyUserToken') | ||
|
||
const actualizarFCMController = require('../controllers/actualizarFCM.controller'); | ||
|
||
router.post('/', verifyToken, actualizarFCMController.actualizarFCM); | ||
|
||
module.exports = router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
const admin = require('./firebase-admin-config'); | ||
const { | ||
Usuario | ||
} = require('../models/perfil/usuario.model'); | ||
|
||
const chunkArray = (array, size) => { | ||
const result = []; | ||
for (let i = 0; i < array.length; i += size) { | ||
result.push(array.slice(i, i + size)); | ||
} | ||
return result; | ||
}; | ||
|
||
const sendNotification = async (tokens, titulo, cuerpo, data = {}) => { | ||
if (!tokens || tokens.length === 0) { | ||
console.log('No hay tokens de FCM para enviar notificaciones.'); | ||
return; | ||
} | ||
|
||
// Dividir los tokens en grupos de 500 como máximo | ||
const tokenChunks = chunkArray(tokens, 500); | ||
|
||
try { | ||
for (const chunk of tokenChunks) { | ||
const responses = await admin.messaging().sendEachForMulticast({ | ||
tokens: chunk, | ||
notification: { | ||
title: titulo, | ||
body: cuerpo, | ||
}, | ||
data: data | ||
}); | ||
|
||
let successCount = 0; | ||
let failureCount = 0; | ||
const failedTokens = []; | ||
|
||
responses.responses.forEach((response, index) => { | ||
if (response.success) { | ||
successCount++; | ||
} else { | ||
failureCount++; | ||
const failedToken = chunk[index]; | ||
console.error(`Error al enviar a ${failedToken}: ${response.error.message}`); | ||
if ( | ||
response.error.code === 'messaging/invalid-registration-token' || | ||
response.error.code === 'messaging/registration-token-not-registered' | ||
) { | ||
failedTokens.push(failedToken); | ||
} | ||
} | ||
}); | ||
|
||
console.log(`${successCount} mensajes enviados con éxito`); | ||
console.log(`${failureCount} mensajes fallaron`); | ||
|
||
// Si hay tokens fallidos, eliminarlos de la base de datos | ||
if (failedTokens.length > 0) { | ||
await Usuario.updateMany({ | ||
fcmTokens: { | ||
$in: failedTokens | ||
} | ||
}, { | ||
$pull: { | ||
fcmTokens: { | ||
$in: failedTokens | ||
} | ||
} | ||
}); | ||
console.log('Tokens inválidos eliminados de la base de datos.'); | ||
} | ||
} | ||
} catch (error) { | ||
console.error('Error al enviar notificaciones:', error); | ||
} | ||
}; | ||
|
||
module.exports = sendNotification; |