algolia / firestore-algolia-search

Apache License 2.0
112 stars 35 forks source link

Firebase Cloud functions error 'Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com' #88

Closed dipinsonwani closed 2 years ago

dipinsonwani commented 2 years ago

When I deploy the algolia search in my app it works really well. But the other cloud functions which I have deployed works only when algolia search is not deployed. I get the following error in the logs Unreachable hosts - your application id may be incorrect.

My application Id is correct and I am using the firebase blaze plan.

Version: "algoliasearch": "^4.11.0",

    "express": "^4.17.2",

    "firebase-admin": "^9.12.0",

    "firebase-functions": "^3.16.0", Sharing my code below

algolia.js

const ALGOLIA_APP_ID = APP_ID;
const functions = require("firebase-functions");
const ALOGOLIA_ADMIN_KEY = API_KEY;
const ALGOLIA_INDEX_NAME = 'profile_card';
const client = algoliasearch(ALGOLIA_APP_ID, ALOGOLIA_ADMIN_KEY);
const index = client.initIndex(ALGOLIA_INDEX_NAME);

index.setSettings({ searchableAttributes: ['username', '_tags'], attributesForFaceting: ['searchable(_tags)'], removeStopWords: true });
exports.createPost = functions.firestore
    .document('EUU/{euId}')
    .onCreate(async (snap, context) => {
        const newValue = snap.data();
        newValue.objectID = snap.id;
        return index.saveObject(newValue);
        console.log('Finished');
    });

exports.updatePost = functions.firestore
    .document('EUU/{euId}')
    .onUpdate(async (snap, context) => {
        const afterUpdate = snap.after.data();
        afterUpdate.objectID = snap.after.id;
        return index.saveObject(afterUpdate);
    });

exports.deletePost = functions.firestore
    .document('EUU/{euId}')
    .onDelete(async (snap, context) => {
        const oldID = snap.id;
        return index.deleteObject(oldID);
    });

index.js

const functions = require("firebase-functions");
const admin = require('firebase-admin');
const algo = require('./algolia');
// const cashfree = require('./cashfree');
admin.initializeApp(functions.config().functions);

const options = {
  priority: 'high'
}
exports.sendRequest = functions.firestore.document('EUU/{euId}/Requests/{id}').onCreate(async (snapshot, context) => {
  const request = snapshot.data();
  // console.log(context.params.euId);
  admin.firestore().collection('mobileNotificationToken').doc(context.params.euId).get().then((doc) => {
    const deviceTokens = doc.get('tokens');
    // console.log(deviceTokens);
    var payload = {
      notification: {
        title: 'Session request from ' + request.sender_name,
        body: 'Time slot: ' + request.time_slot,

      },
      data: {
        tag: 'request',
        'reason': request.reason,
        request_id: snapshot.id,
        sender_id: context.params.euId,
      },

    };
    return admin.messaging().sendToDevice(deviceTokens, payload, options).catch((error) => {
      // console.log('Error sending message:', error);
      console.error("Request Failed", error)
    })
  });
})
exports.paymentNotif = functions.firestore.document('EUU/{euId}/Requests/{id}').onUpdate(async (change, context) => {
  const updatedStatus = change.after.data();
  if (updatedStatus.status == 'Accepted') {
    admin.firestore().collection('mobileNotificationToken').doc(updatedStatus.sender_id).get().then((doc) => {
      const deviceTokens = doc.get('tokens');
      console.log(deviceTokens);
      var payload = {
        notification: {
          title: `Appointment Accepted by ${updatedStatus.receiver_name}`,
          body: `Your appointment has been accepted`,

        },
        data: {
          message: 'Your Session is booked',
          tag: 'payment',
          sender_id: context.params.euId,
          'request_id': context.params.id,
        },

      };
      const notificaiton = {
        title: `Appointment Accepted by ${updatedStatus.receiver_name}`,
        body: `Your appointment accepted`,
        euId: context.params.euId,
        payment_done: false,
        reqId: context.params.id,
        createdAt: admin.firestore.Timestamp.now(),
        type: 'Type.Payment'
      }
      const docs = admin.firestore().collection('Seeker').doc(updatedStatus.sender_id);
      const EUdocs = admin.firestore().collection('EUU').doc(updatedStatus.sender_id);

      EUdocs.get().then((snap) => {
        if (snap.exists) {
          EUdocs.collection('notifications').add(notificaiton).then(() => console.log('notification stored to db'));

        } else {
          docs.collection('notifications').add(notificaiton).then(() => console.log('notification stored to db'));

        }
      });
      return admin.messaging().sendToDevice(deviceTokens, payload, options)
        .then((response) => {
          console.log("Successfully sent message: ", response);
        }).catch((error) => {
          console.log('Error sending message:', error);
        })
    });
    // const id = change.id;
    // return change.after.ref.set({ id: { 'payment': 'pending' } });

  } else {
    console.log('DIDNT WORK');
  }

})

exports.sendNotification = functions.firestore.document('EUU/{euId}/Notifications/{id}').onCreate(async (snapshot, context) => {
  const request = snapshot.data();
  console.log(context.params.euId);
  admin.firestore().collection('mobileNotificationToken').doc(context.params.euId).get().then((doc) => {
    const deviceTokens = doc.get('tokens');
    console.log(deviceTokens);
    var payload = {
      notification: {
        title: 'Push Notification',
        body: 'Hello',

      },
      data: {
        message: 'Your Session is booked',
        tag: 'notification',
        // receiver_id: context.params.euId,
      },

    };
    admin.messaging().sendToDevice(deviceTokens, payload, options)
      .then((response) => {

        console.log("Successfully sent message: ", response);
      }).catch((error) => {
        console.log('Error sending message:', error);
      })
  });
})

exports.paymentSuccess = functions.firestore.document('Seeker/{seekerId}/Orders/{id}').onUpdate(async (change, context) => {
  const updatedStatus = change.after.data();
  if (updatedStatus.txStatus == 'SUCCESS') {
    admin.firestore().collection('mobileNotificationToken').doc(updatedStatus.euId).get().then((doc) => {
      const deviceTokens = doc.get('tokens');
      console.log(deviceTokens);
      var payload = {
        notification: {
          title: 'Session Confirmation',
          body: 'Your session has been confirmed',

        },
        data: {
          message: 'Your Session is booked',
        },
      };
      return admin.messaging().sendToDevice(deviceTokens, payload, options)
        .then((response) => {
          console.log("Successfully sent message: ", response);
        }).catch((error) => {
          console.log('Error sending message:', error);
        })
    });
    admin.firestore().collection('mobileNotificationToken').doc(updatedStatus.seekerId).get().then((doc) => {
      const deviceTokens = doc.get('tokens');
      console.log(deviceTokens);
      var payload = {
        notification: {
          title: 'Session Confirmation',
          body: 'Your session has been confirmed',

        },
        data: {
          message: 'Your Session is booked',
        },
      };
      return admin.messaging().sendToDevice(deviceTokens, payload, options)
        .then((response) => {
          console.log("Successfully sent message: ", response);
        }).catch((error) => {
          console.log('Error sending message:', error);
        })
    });
    // const id = change.id;
    // return change.after.ref.set({ id: { 'payment': 'pending' } });

  } else {
    console.log('PAYMENT SUCCESS DIDNT WORK');
  }

});
exports.createPost = algo.createPost;
exports.deletePost = algo.deletePost;
exports.updatePost = algo.updatePost;

Screenshot (17)

smomin commented 2 years ago

I don't completely understand but looking at algolia.js, I am curious if algolia app id and keys are being set. Can you verify by console.log out your algolia app id?

dipinsonwani commented 2 years ago

Yes I have set app Id and API key directly. I have removed in this code for security. As all the search functions are working including index getting updated.

smomin commented 2 years ago

Can you also open a ticket with Firebase? This could be a configuration issue.

dipinsonwani commented 2 years ago

Yes I will do that

Haroenv commented 2 years ago

if I remember it correctly you also get this error if not on the blaze plan on firebase, as it blocks outgoing requests, is that possible in your case?

smomin commented 2 years ago

hey @dipinsonwani, did the Firebase team provide any directions or help to resolve your issue?