[javascript] scheduled
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- exports.scheduleAsyncMorningNotif = functions.pubsub.schedule('10 08 * * *')
- .timeZone('America/Chicago')
- .onRun((context) => {
- const tsToMillis = admin.firestore.Timestamp.now().toMillis();
- const today = new Date(tsToMillis + (15 * 60 * 60 * 1000));
- const userPlants = db.collection('UserPlants');
- let lastVisible = null;
- let totalSuccessCount = 0;
- function handleUserPlantsFCM() {
- const snapshot = !!lastVisible ? userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").startAfter(lastVisible).limit(500).get()
- : userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").limit(500).get();
- if (snapshot.empty) {
- console.log('No matching documents.');
- return;
- }
- snapshot.then(async function(querySnapshot) {
- console.log('Query Snapshot of UserPlants showing as:', querySnapshot.size);
- lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
- var messages = [];
- querySnapshot.forEach((doc) => {
- const data = doc.data();
- const { plantName, userFCMToken } = data;
- if (plantName && userFCMToken) {
- const message = {
- notification: {
- title: 'You have a plant to save! 🌱',
- body: `Your ${plantName} needs some water - make sure to take care of it! ☔️`,
- },
- token: userFCMToken
- };
- messages.push(message);
- } else {
- console.log('Nil/false on user token, skipping for now');
- }
- });
- if (!!messages.length) {
- try {
- const response = await admin.messaging().sendAll(messages);
- totalSuccessCount += response.successCount;
- } catch(err) {
- console.log(err);
- }
- messages = [];
- }
- handleUserPlantsFCM();
- });
- }
- handleUserPlantsFCM();
- console.log(totalSuccessCount + ' messages were sent successfully');
- return null;
- });
Editor
You can edit this paste and save as new: