firebase cloud function firestore not being triggered with region europe-west1 - firebase

I am testing the new region settings for Firebase cloud functions something is not right (I may be doing something wrong).
Since our users are in europe i wanted to move all my project and my functions to europe.
Https functions are working as expected, just setting this:
export const test = region('europe-west1').https.onRequest(....)
On the other hand, I am having troubles with the firebase triggers. While this function works fine:
export const firebaseUpdateTrigger = region('us-central1')
.firestore
.document(...)
.onUpdate(...)
The same code just like this does not get triggered:
export const firebaseUpdateTrigger = region('europe-west1')
.firestore
.document(...)
.onUpdate(...)
What is it that I am doing wrong??
I am using these versions:
"firebase-functions": "2.0.4",
"firebase-admin": "5.13.1",
"#google-cloud/firestore": "^0.15.0"

You might have missed some of the required steps, to change a function's region, namely:
Rename the function, and change its region.
Deploy the renamed function, which results in temporarily running the same code in both regions.
Delete the previous function
You may gather more detail from the "Change a function's region" sub-chapter of the "Manage functions deployment and runtime options" online document.

Hey there #Borja Gorriz
I just had a similar issue, this one worked out for me:
exports.onTest2 = functions.region('europe-west2').firestore
.document('/mycollection/{documentID1}')
.onUpdate((change, context) => {
console.log('test all right');
});
Successful deployment:

after creating the function with same name I was getting the issue, that the event onCreate is not getting triggered. So, I deleted the old function (in old region) which I don't need. Then I deployed the again. It solved my problem.
deleted the old function
redeployed the new function

Related

How do I return the custom metaData from firebase storage, using the admin.storage() method

so I am trying to add image moderation to my firebase app, using this guide here here is the repo and this also might be useful. I tested it out and it seems to work well, however I wanted to update the same image from storage, not upload it to a separate path. This caused the firebase function to fire recursively and I cost my company a couple of dollars. To solve this I decided whenever an image is uploaded there would be custom metadata saying if it has been blurred or not. The code for this is down below and works.
const metaData = {
customMetadata: {
blurred: 'false',
},
}
const imageBytes = await uploadBytesResumable(storageRef, blobFile, metaData);
Now in my firebase function every time an image is uploaded it will check the object.metaData to see if it is equal to 'true'. Here is the code down below for that.
export const blurOffensiveImages = functions.storage.object().onFinalize(async (object) => {
// Ignore things we've already blurred
if (object.metadata?.customMetadata.blurred === 'true') {
functions.logger.log(`meta datas are the same, stopping function`);
return null;
}
If the metadata is equal to false then it will run the normal function and check if the image is worth blurring. If it is then all it does is change the metadata to true since this will stop the recursion.
My problem, I am having type errors saying 'Property "blurred' does not exist on type 'string'". I have played around with this for a while and cant seem to find a solution to get the customMetaData to come out the way I would like. If i remove the .blurred I get no errors but I also know this would not give the correct data when I check if it is equal to 'true'or 'false'. If anyone knows how to fix this that would be really appreciated. OR if someone has a good solution to stop this recurson from happening that would also be great since this has been giving me issues for a few days. Thanks!

Sanity Groq function - array of unique values

I need some help regarding fetching some data.
I'm building blog with Nuxt3 and Sanity and I use https://sanity.nuxtjs.org/ module.
I need query to get all the unique tags from _type article so I can have filter by tags in my blog.
I wrote this query and It gives result back in my Sanity Vision.
array::unique(*[_type == "article" ].tag.value)
However When I run it in project I get data null. Here is how I try.
const query = groq`array::unique(*[_type == "article" ].tag.value)`
const { fetch } = useSanity()
const { data } = await useAsyncData("article tags", () => fetch(query))
I guess I'm doing something wrong with using Sanity Groq Functions.
It was problem with different versions of Sanity API.
When using #nuxtjs/sanity module the API version by default is 1.
Inside my Sanity studio vision I was testing query with newer version therefor it worked.
I updated sanity configuration inside my nuxt.config and now everything works.

Google Cloud Datastore "out of bounds of 'Number.MAX_SAFE_INTEGER'"

One of the data in datastore is 7766277975020011920 and similarities.
The error shown in nodejs is -
Error: We attempted to return all of the numeric values, but chain value 7766277975129421920 is out of bounds of 'Number.MAX_SAFE_INTEGER'.
It suggested "options.wrapNumbers=true" to the file
"node_modules/#google-cloud/datastore/build/src/entity.js:412:19".
But I am using google cloud RUN version and not able to edit the files. How can I pass it ?
Moving my comment into an answer, according to the Node.js client reference for Datastore, when you run queries or calls for entities, you can pass options as an additional argument, which supports passing the wrapNumbers = True option:
const [values] = await datastore.runQuery(query,{"wrapNumbers":true});
You can use that in your calls to avoid receiving out of bounds errors for large integers. The rest of the supported options are documented in this code snippet from the official repository:
const options = {
consistency: 'string',
gaxOptions: {},
wrapNumbers: true,
};

Firebase (single) document trigger stopped working

As storage triggers are bucket-wide, I'm using a firestore trigger to watch changes in the "UploadTriggers/" path where the docId labels each target file (this is a small static list) and the storage_path entry in that doc points to where I've updoaded the file.
This worked great right of of the gate, but it has just stopped working. (I tried reducing the whole fn to a single console.log, but still nothing.)
There is no log output at all, and no indication of failure - just nothing.
I've tried re-deploying the fn's (with and w/o a rename) to no avail.
Any ideas?
export const myFn = functions.firestore
.document('UploadTriggers/MyFile.csv')
.onWrite(async (change, context) => {
const path = changed.after.data().storage_path;
console.log("csv updated:", path);
// ...load stream from path and do neat things...
Turns out that it was working fine -- it was a combination of the fn taking much longer to execute than expected (something in centralus?) and the rather bizarre way that logs are presented in the firebase dashboard -- it seems to present some random subset of the logs at any given moment.

Firebase Full-Text Search using Algolia

I configured different firebase functions by following this
. Now in this, there is firebase full-text search. I tried to follow it but it seems to be incomplete. I have searched and somehow got success in deploying. But it is still not creating index in Algolia. Can someone tell me the steps to correctly perform this?
I created the blog-posts and search nodes in my firebase project but problem is still there.
CODE:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Authenticate to Algolia Database.
// TODO: Make sure you configure the `algolia.app_id` and `algolia.api_key` Google Cloud environment variables.
const algoliasearch = require('algoliasearch');
const client = algoliasearch(functions.config().algolia.app_id, functions.config().algolia.api_key);
// Name fo the algolia index for Blog posts content.
const ALGOLIA_POSTS_INDEX_NAME = 'blogposts';
// Updates the search index when new blog entries are created or updated.
exports.indexentry = functions.database.ref('/blog-posts/{blogid}/text').onWrite(event => {
const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME);
const firebaseObject = {
text: event.data.val(),
objectID: event.params.blogid
};
return index.saveObject(firebaseObject).then(
() => event.data.adminRef.parent.child('last_index_timestamp').set(
Date.parse(event.timestamp)));
});
// Starts a search query whenever a query is requested (by adding one to the `/search/queries`
// element. Search results are then written under `/search/results`.
exports.searchentry = functions.database.ref('/search/queries/{queryid}').onWrite(event => {
const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME);
const query = event.data.val().query;
const key = event.data.key;
return index.search(query).then(content => {
const updates = {
'/search/last_query_timestamp': Date.parse(event.timestamp)
};
updates[`/search/results/${key}`] = content;
return admin.database().ref().update(updates);
});
});
SEE IMAGE OF FIREBASE NODE
Open Image
Your help will be appreciated. Thanks
So I used the sample code provided here and placed it into a Firebase cloud function. Writing to '/blog-posts/{blogid}/text' inside the database should index whatever value is under text to Algolia.
There are a few things that might be going wrong here:
Check that your function is correctly placed into Firebase. You can do this from the console by clicking functions on the left side. You should see two functions named indexentry and searchentry. If you do not see those functions then you haven't correctly pushed your code to the Firebase cloud.
If you code is in Firebase cloud then I recommend adding console.log("write on blog-posts fired"); to your searchentry function. Then write some more data to your database under '/blog-posts/{blogid}/text'. You can check the function log in the Firebase console. I have noticed a slight delay in log records displaying some times, so be patient if you don't see it right away. I'd write a few pieces of data to '/blog-posts/{blogid}/text' then after a couple minutes I'd check the log. If the log has "write on blog-posts fired" in it then you know the function is being activated when you write to the database.
If all the above is operating correctly and you still don't have any data in Algolia then make sure you set your API keys. You can do this using the code firebase functions:config:set algolia.app_id="myAlgoliaAppId" algolia.api_key="myAlgoliaApiKey". You run this command in a terminal window inside the directory where you have your Firebase cloud functions. You can get you API keys by signing into your account. Remember not to share your API key with anyone.

Resources