I am developing an application on Android (flight schedule) and the need has arisen to notify all devices about changes to the schedule database: adding a flight, changing the departure time, canceling a flight, delays, etc. Initially I used Service with Listener, but it doesn’t live for long, and therefore it’s not reliable, I decided to configure Firestore so that, with any changes to the database, notifications were sent on flights to all devices where the application is installed. The only thing that was able to find is of. documentation on Function and triggers, but how to prescribe these conditions and where it’s not quite clear (something about Node.js and servers, but I don’t use my server). In Russian, the documentation is even less. Please tell me how to add this functionality of automatic distribution of notifications to Firebase, where you can read with real examples?
- So I understand that you need to deploy a function on the Firebase server through the CLI in the JS language, which you still need to learn ... If I’m right, I’m grateful for the link to a small tutorial on this topic. - Mikhail
|
1 answer
Yes, you rightly noticed that you need to write on NodeJs. Here is a small example:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); // функция, отсылающая уведомления, если произошло изменение документа entryId exports.notifyClient = functions.firestore .document('Collection/{entryId}') .onUpdate((change, context) => { const newValue = change.after.data(); var status = ""; if(newValue.status == "Что-то со статусом"){ status = "Статус " + newValue['someValue']; }else{ status = newValue['someValue']; } var userRef = admin.firestore().collection('Users').doc(newValue.clientID); return userRef.get().then(doc =>{ if(doc.exists && doc.data().token){ const token = doc.data().token; // token девайса пользователя const payload = { data: { sound: "default", badge: "1", title: "Уведомление", tag: "entry", body: status } }; admin.messaging().sendToDevice(token, payload); } }) });
|