Created
April 30, 2019 08:19
-
-
Save Bambina-zz/ecf93bf60fb99f9bcc9bf0a66cde0de7 to your computer and use it in GitHub Desktop.
A cloud function which sends data notification to all users stored in Firestore.
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
const functions = require('firebase-functions'); | |
// // Create and Deploy Your First Cloud Functions | |
// // https://firebase.google.com/docs/functions/write-firebase-functions | |
// | |
// exports.helloWorld = functions.https.onRequest((request, response) => { | |
// response.send("Hello from Firebase!"); | |
// }); | |
// Import the Firebase SDK for Google Cloud Functions. | |
const functions = require('firebase-functions'); | |
// Import and initialize the Firebase Admin SDK. | |
const admin = require('firebase-admin'); | |
admin.initializeApp(); | |
exports.sendNotificationApi = functions.https.onRequest((req, res) => { | |
sendMessage().then(val => { | |
res.status(200).send(val); | |
}).catch(val => { | |
res.status(500).send(val); | |
}); | |
}); | |
async function sendMessage() { | |
// Notification details. | |
const payload = { | |
data: { | |
title: "Cloud Messaging", | |
message: "Open the app right now, please.", | |
} | |
}; | |
// Get the list of device tokens. | |
const allTokens = await admin.firestore().collection('fcmTokens').get(); | |
const tokens = []; | |
allTokens.forEach((tokenDoc) => { | |
tokens.push(tokenDoc.id); | |
}); | |
if (tokens.length > 0) { | |
// Send notifications to all tokens. | |
const response = await admin.messaging().sendToDevice(tokens, payload); | |
await cleanupTokens(response, tokens); | |
console.log('Notifications have been sent and tokens cleaned up.'); | |
} | |
return "OK"; | |
} | |
// Cleans up the tokens that are no longer valid. | |
function cleanupTokens(response, tokens) { | |
// For each notification we check if there was an error. | |
const tokensDelete = []; | |
response.results.forEach((result, index) => { | |
const error = result.error; | |
if (error) { | |
console.error('Failure sending notification to', tokens[index], error); | |
// Cleanup the tokens who are not registered anymore. | |
if (error.code === 'messaging/invalid-registration-token' || | |
error.code === 'messaging/registration-token-not-registered') { | |
const deleteTask = admin.firestore().collection('messages').doc(tokens[index]).delete(); | |
tokensDelete.push(deleteTask); | |
} | |
} | |
}); | |
return Promise.all(tokensDelete); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment