Algolia search error when "index.addObject()" - javascript

I've installed algolia using this tutorial: https://www.youtube.com/watch?v=dTXzxSlhTDM
I have firestore paid version and all was going okay till i created an item in my collection to try if it was working, but when i did it any item was added in my algolia index, so i went to cloud functions log and saw this:
addToIndex
TypeError: index.addObject is not a function
at exports.addToIndex.functions.firestore.document.onCreate.snapshot (/srv/index.js:15:22)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
I wasted 30 mins looking at the code, and rewriting it all perfectly exact as in the video, and searched for this error and didn't find anything, so here i'm
index.js
const functions = require('firebase-functions');
const algoliasearch = require('algoliasearch');
const APP_ID = functions.config().algolia.app;
const ADMIN_KEY = functions.config().algolia.key;
const client = algoliasearch(APP_ID, ADMIN_KEY);
const index = client.initIndex('items');
exports.addToIndex = functions.firestore.document('items/{itemId}')
.onCreate(snapshot => {
const data = snapshot.data();
const objectID = snapshot.id;
return index.addObject({ ...data, objectID });
});
exports.updateIndex = functions.firestore.document('items/{itemId}')
.onUpdate((change) => {
const newData = change.after.data();
const objectID = change.after.id;
return index.saveObject({ ...newData, objectID });
});
exports.deleteFromIndex = functions.firestore.document('items/{itemId}')
.onDelete(snapshot => index.deleteObject(snapshot.id));

The addObject method doesn't exist on the latest version. You have to use saveObject:
index.saveObject({ ...data, objectID })
Note that a tutorial for Algolia is available in Firebase documentation.

Related

Firebase Function query and update a single Firestore document

I am trying to update a user's firestore doc from a Firebase Function using a query, and having issues getting it to work. My Function code is the following:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
/**
* A webhook handler function for the relevant Stripe events.
*/
// Here would be the function that calls updatePlan and passes it the customer email,
// I've omitted it to simplify the snippet
const updatePlan = async (customerEmail) => {
await admin.firestore()
.collection('users').where('email', '==', customerEmail).get()
.then((doc) => {
const ref = doc.ref;
ref.update({ 'purchasedTemplateOne': true });
});
};
I'm getting the following error in the firebase logs when the query is run:
Exception from a finished function: TypeError: Cannot read properties of undefined (reading 'update')
Any help regarding what I may be doing wrong or suggestions on how I could achieve this would be greatly appreciated, Thank you in advance!
Update:
I was able to solve my problem with more understanding of Firestore Queries:
const updatePlan = (customerEmail) => {
const customerQuery = admin.firestore().collection("users").where("email", "==", customerEmail)
customerQuery.get().then(querySnapshot => {
if (!querySnapshot.empty) {
// Get just the one customer/user document
const snapshot = querySnapshot.docs[0]
// Reference of customer/user doc
const documentRef = snapshot.ref
documentRef.update({ 'purchasedTemplateOne': true })
functions.logger.log("User Document Updated:", documentRef);
}
else {
functions.logger.log("User Document Does Not Exist");
}
})
};
The error message is telling you that doc.ref is undefined. There is no property ref on the object doc.
This is probably because you misunderstand the object that results from a Firestore query. Even if you are expecting a single document, a filtered query can return zero or more documents. Those documents are always represented in an object of type QuerySnapshot. That's what doc actually is - a QuerySnapshot - so you need to treat it as such.
Perhaps you should check the size of the result set before you access the docs array to see what's returned by the query. This is covered in the documentation.

Javascript functions in firebase

Getting the following error:
"Cannot read property 'userName' of undefined
at Promise.all.then.result"
Also Getting Error
"The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK.
To hide this warning and ensure your app does not break, you need to add the
following code to your app before calling any other Cloud Firestore methods:
const firestore = new Firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
With this change, timestamps stored in Cloud Firestore will be read back as
Firebase Timestamp objects instead of as system Date objects. So you will also
need to update code expecting a Date to instead expect a Timestamp. For example:
// Old:
const date = snapshot.get('created_at');
// New:
const timestamp = snapshot.get('created_at');
const date = timestamp.toDate();
Please audit all existing usages of Date when you enable the new behavior. In a
future release, the behavior will change to the new behavior, so if you do not
follow these steps, YOUR APP MAY BREAK."
However in my android project the place where i have defined the "Date" variable i have place the "#ServerTimestamp" on top.
Appreciate the help guys.
Code:
/*eslint-disable */
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document('notifications/{userEmail}/userNotifications/{notificationId}').onWrite((change, context) => {
const userEmail = context.params.userEmail;
const notificationId = context.params.notificationId;
return admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).get().then(queryResult => {
const senderUserEmail = queryResult.data().senderUserEmail;
const notificationMessage = queryResult.data().notificationMessage;
const fromUser = admin.firestore().collection("users").doc(senderUserEmail).get();
const toUser = admin.firestore().collection("users").doc(userEmail).get();
return Promise.all([fromUser, toUser]).then(result => {
const fromUserName = result[0].data().userName;
const toUserName = result[1].data().userName;
const tokenId = result[1].data().tokenId;
const notificationContent = {
notification: {
title: fromUserName + " is shopping",
body: notificationMessage,
icon: "default"
}
};
return admin.messaging().sendToDevice(tokenId, notificationContent).then(result => {
console.log("Notification sent!");
//admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).delete();
});
});
});
});
Make sure the document you're request actually exists. data() will return undefined if it doesn't. You can use the exists property on the resulting DataSnapshot to check if a document was actually found.

can't get params from firebase function

I'm currently trying to send a confirmation email with sendgrid API from a firebase function.
The API is not the problem though, it seems to work fine, my problem is that I can't get the child oncreate's value (Firebase function log):
TypeError: Cannot read property 'participant_id' of undefined
at exports.SendEmail.functions.database.ref.onCreate.event (/user_code/index.js:15:38)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:716:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
And here's my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const SENDGRID_API_KEY = functions.config().sendgrid.key;
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);
exports.SendEmail = functions.database.ref('participants/{participant_id}').onCreate(event => {
const participant_id = event.params.participant_id;
const db = admin.database();
return db.ref(`participants/${participant_id}`).once('value').then(function(data){
const user = data.val();
const email = {
to: user.email,
from: 'recrutement.cisssme16#ssss.gouv.qc.ca',
subject: "Bienvenue au Blitz d'embauche 2018!",
templateId: 'dd3c9553-5e92-4054-8919-c47f15d3ecf6',
substitutionWrappers: ['<%', '%>'],
substitutions: {
name: user.name,
num: user.num
}
};
return sgMail.send(email)
})
.then(() => console.log('email sent to', user.email))
.catch(err => console.log(err))
});
This is not my first firebase function. I even copied pasted previous working codes which worked fined and I still get an undefined value!
What's the problem here? Did firebase changed event.params?
Also my participant_id is an integer value (ex.: 3827), if that changes something.
Thanks in advance!
The signature of the function is wrong, take a look at this example on Handle event data:
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onCreate((snapshot, context) => {
console.log('Uppercasing', context.params.pushId, original);
});
So just adjust your onCreate function and you'll be all set :)

How to solve this Firebase cloud function Error: Cannot read property

I am following a tutorial where I am adding some Firebase Cloud Functions to my project (step 5). I have successfully deployed my cloud function to firebase but nothing happens when I add a new product manually in the Firebase Database console. I discovered that the Firebase cloud function is triggered but it is getting an error: "TypeError: Cannot read property 'productId' of undefined"
What am I doing wrong?
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.sendMessage = functions.firestore
.document('products/{productId}')
.onCreate(event => {
const docId = event.params.productId; // <-- error here
const name = event.data.data().name;
const productRef = admin.firestore().collection('products').doc(docId)
return productRef.update({ message: `Nice ${name}! - Love Cloud Functions`})
});
That tutorial must be out of date. Some things have changed in the Functions SDK when it released version 1.0. You can read about those changes here.
Database triggers are now passed two parameters instead of one. The new context parameter contains the value of wildcards in the reference path:
exports.sendMessage = functions.firestore
.document('products/{productId}')
.onCreate((snapshot, context) => {
const docId = context.params.productId;
If you want to continue with that tutorial, you'll have to manually convert all of its old stuff to new stuff.
OK. So thanks to Dough Stevensson's answer notifying me that the syntax was old I have now a solution:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
exports.sendMessage = functions.firestore
.document('products/{productId}')
.onCreate((snapshot, context) => {
const docId = context.params.productId;
const productRef = db.collection('products').doc(docId)
return productRef.update({ message: `Nice ${name}!`})
});

Firebase cloud functions for crashlytics are not triggering

So we have a project, in which Crashlytics and analytics are set-up and currently functioning. However I am not able to successfully implement the cloud functions for the three triggers found here : Crashlytics Events.
While testing using other cloud functions such as when there are read/write operations on the database, the functions execute correctly. When deploying the functions folder to firebase, I get no errors in regards to the triggers and the code is very similar to the samples on Github. I have made sure that the SDK is up to date and that I have run npm install in the functions folder for any dependencies.
Here is the JS file:
'use strict';
const functions = require('firebase-functions');
const rp = require('request-promise');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Helper function that posts to Slack about the new issue
const notifySlack = (slackMessage) => {
// See https://api.slack.com/docs/message-formatting on how
// to customize the message payload
return rp({
method: 'POST',
uri: functions.config().slack.webhook_url,
body: {
text: slackMessage,
},
json: true,
});
};
exports.postOnNewIssue = functions.crashlytics.issue().onNewDetected((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const slackMessage = `<!here|here> There is a new issue - ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform}`;
return notifySlack(slackMessage).then(() => {
return console.log(`Posted new issue ${issueId} successfully to Slack`);
});
});
exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const resolvedTime = data.resolvedTime;
const slackMessage = `<!here|here> There is a regressed issue ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform}. This issue was previously ` +
`resolved at ${new Date(resolvedTime).toString()}`;
return notifySlack(slackMessage).then(() => {
return console.log(`Posted regressed issue ${issueId} successfully to Slack`);
});
});
exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const crashPercentage = data.velocityAlert.crashPercentage;
const slackMessage = `<!here|here> There is an issue ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform} that is causing ` +
`${parseFloat(crashPercentage).toFixed(2)}% of all sessions to crash.`;
return notifySlack(slackMessage)/then(() => {
console.log(`Posted velocity alert ${issueId} successfully to Slack`);
});
});
When I tried to deploy Crashlytics events, I was greeted with the following error message.
⚠ functions: failed to update function crashlyticsOnRegressed
HTTP Error: 400, The request has errors
⚠ functions: failed to update function crashlyticsOnNew
HTTP Error: 400, The request has errors
⚠ functions: failed to update function crashlyticsOnVelocityAlert
HTTP Error: 400, The request has errors
Sure enough, Cloud Function documentation no longer lists Crashlytics, which used to be under the section Crashlytics triggers. Perhaps Google no longer supports it.
According to this issue, the crashlytics function triggers were deprecated and removed in release 3.13.3 of the firebase-functions SDK.

Categories