[javascript] scheduled

Viewer

copydownloadembedprintName: scheduled
  1. exports.scheduleAsyncMorningNotif = functions.pubsub.schedule('10 08 * * *')
  2. .timeZone('America/Chicago')
  3. .onRun((context) => {
  4.     const tsToMillis = admin.firestore.Timestamp.now().toMillis();
  5.     const today = new Date(tsToMillis + (15 * 60 * 60 * 1000));
  6.     
  7.     const userPlants = db.collection('UserPlants');
  8.     
  9.     let lastVisible = null;
  10.     let totalSuccessCount = 0;
  11.     
  12.     function handleUserPlantsFCM() {
  13.         const snapshot = !!lastVisible ? userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").startAfter(lastVisible).limit(500).get() 
  14.         : userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").limit(500).get();
  15.                         
  16.         if (snapshot.empty) {
  17.             console.log('No matching documents.');
  18.             return;
  19.         }
  20.     
  21.         snapshot.then(async function(querySnapshot) {
  22.             console.log('Query Snapshot of UserPlants showing as:', querySnapshot.size);
  23.             lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
  24.             var messages = [];
  25.             querySnapshot.forEach((doc) => {
  26.                 const data = doc.data();
  27.                 const { plantName, userFCMToken } = data;
  28.                 if (plantName && userFCMToken) {
  29.                     const message = {
  30.                         notification: {
  31.                             title: 'You have a plant to save! 🌱',
  32.                             body: `Your ${plantName} needs some water - make sure to take care of it! ☔️`,
  33.                         },
  34.                         token: userFCMToken
  35.                     };
  36.                     messages.push(message);
  37.                 } else {
  38.                   console.log('Nil/false on user token, skipping for now');
  39.                 }
  40.             });
  41.             if (!!messages.length) {
  42.                 try {
  43.                     const response  = await admin.messaging().sendAll(messages);
  44.                     totalSuccessCount += response.successCount;
  45.                 } catch(err) {
  46.                     console.log(err);
  47.                 }
  48.                 messages = [];
  49.             }
  50.             
  51.             handleUserPlantsFCM();
  52.         });
  53.     }
  54.     
  55.     handleUserPlantsFCM();
  56.     console.log(totalSuccessCount + ' messages were sent successfully');
  57.     
  58.     return null;
  59. });

Editor

You can edit this paste and save as new:


File Description
  • scheduled
  • Paste Code
  • 14 Jun-2021
  • 2.41 Kb
You can Share it: