Facebook
From node, 1 Month ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 136
  1. const functions = require("firebase-functions");
  2. const admin = require("firebase-admin");
  3. const { error } = require("firebase-functions/logger");
  4. const { projectID } = require("firebase-functions/params");
  5. var serviceAccount = require("./rhsite-web-firebase-adminsdk-ds235-6b597b7ee3.json");
  6. // const { DateTime } = require('luxon');
  7.  
  8. admin.initializeApp({
  9.     credential: admin.credential.cert(serviceAccount)
  10.   });
  11. const database = admin.firestore();
  12.  
  13. exports.sendNotificationForDates = functions.pubsub.schedule('* * * * *').onRun(async (context) => {
  14.   try {
  15.     const habitsSnapshot = await admin.firestore().collection('natural_app_active_habits').get();
  16.     console.log('Function started');
  17.        habitsSnapshot.forEach((habitDoc) => {
  18.       const habitData = habitDoc.data();
  19.       const { fcmToken, userId, talkingCricketId, item ,dates} = habitData;
  20.  
  21.    
  22.       dates.forEach(date => {
  23.         console.log(' habit dates ===============> ',dates);
  24.      
  25.       const currentTime = new Date();
  26.       const currentHourMinute = currentTime.toLocaleString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit', hour12: false, hour: '2-digit', minute: '2-digit' });
  27.     //   console.log(' current date and time ===============> ',currentHourMinute);
  28.    
  29.         const dateObj = new Date(date.seconds * 1000); // Convert Firestore timestamp to JavaScript Date object
  30.         const habitHourMinute = dateObj.toLocaleString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit', hour12: false, hour: '2-digit', minute: '2-digit' });
  31.         console.log(' habit date and time ===============> ',habitHourMinute);
  32.         if (habitHourMinute === currentHourMinute) {
  33.           const payload = {
  34.             notification: {
  35.               title: item.title,
  36.               body: item.description,
  37.               imageUrl: item.image, // Assuming you want to include image URL in notification
  38.             },
  39.             data: {
  40.               userId: userId,
  41.             }
  42.           };
  43.  
  44.           // Send notification to user
  45.           admin.messaging().sendToDevice(fcmToken, payload)
  46.             .then(async(response) => {
  47.               console.log('Notification sent successfully:', response);
  48.               await admin.firestore().collection('natural_app_notifications').add({
  49.                 userId: userId,
  50.                 title: item.title,
  51.                 description: item.description,
  52.                 imageUrl:item.image,
  53.                 talkingCricketItem:item,
  54.                 createdAt: admin.firestore.FieldValue.serverTimestamp()
  55.               });
  56.             })
  57.             .catch((error) => {
  58.               console.error('Error sending notification:', error);
  59.             });
  60.            
  61.         }
  62.       });
  63.     });
  64.   } catch (error) {
  65.     console.error('Error in Cloud Function:', error);
  66.   }
  67. });
  68.