How to implement a counter function using firebase functions? - node.js

I WANT TO IMPLEMENT A COUNTER FUNCTION USING FIREBASE FUNCTION TO COUNT NO OF TIMES MY APP IS BEING OPENED.
What I want:
Android app opened---> app calling ------>firebase function executed via http trigger------->firebase function increment value stored in firebase database
How to read and update data on firebase realtime database from firebase Functions.
I made an Firebase function which triggers on http triggers.
Code:
const functions = require('firebase-functions');
exports.counterFunction = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase");
******Code to increment value in firebase database*********
});
I have a field in firebase realtime database called count and 0 corresponds to it
count : 0
I want to increment count variable every time the firebase function is executed
IN SHORT I WANT TO IMPLEMENT A COUNTER USING FIREBASE.
I just want to record the number of times my app started . So I am calling the Http Trigger function using http request using 'okhttp' and the function need to increment the count.

The following Firebase function example should help you understand how to write to the realtime database from a function
https://github.com/firebase/functions-samples/tree/3b41b2e04d854a821a0149e1e5b0769bad397d67/quickstarts/uppercase
Have also a look at https://firebase.google.com/docs/functions/get-started

You could try:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = admin.initializeApp();
exports.counterFunction = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase");
return app.database().ref(`/count`).once('value', (snap) => {
const value = snap.val() || 0;
return app.database().ref(`/count`).set(value + 1).then(res => {
return true;
}).catch(err => {
return Promise.reject(err);
});
});
});
This will increment your counter each time your cloud function is executed.

Related

Google cloud functions - setInterval function quits after 15 mins

My app uses a Firebase function that is triggered when my Firebase realtime database is modified.
The function initiates a setInterval function that is supposed to loop for an hour then terminate....HOWEVER it seems to quit after 15mins.
Im guessing this is a restriction put in place by Firebase...does anyone know how I can get around this?See code below
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//this gets triggered when db is updated
exports.onActiveUpdate = functions.database
.ref('/pathToRealtimeDb').onUpdate(() => {
let counter = setInterval(() => {
//count down from 60 mins to zero then exit
}, 60000); //end setInterval
});

How to use firebase cloud functions' firestore.onWrite() in netlify lamda

I want to aggregate firestore data but I want to go with netlify lambda for the serverless functions. I want to do something like
onst functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.aggregateComments = functions.firestore
.document('posts/{postId}/comments/{commentId}')
.onWrite(event => {
const commentId = event.params.commentId;
const postId = event.params.postId;
// ref to the parent document
const docRef = admin.firestore().collection('posts').doc(postId)
// get all comments and aggregate
return docRef.collection('comments').orderBy('createdAt', 'desc')
.get()
.then(querySnapshot => {
// get the total comment count
const commentCount = querySnapshot.size
const recentComments = []
// add data from the 5 most recent comments to the array
querySnapshot.forEach(doc => {
recentComments.push( doc.data() )
});
recentComments.splice(5)
// record last comment timestamp
const lastActivity = recentComments[0].createdAt
// data to update on the document
const data = { commentCount, recentComments, lastActivity }
// run update
return docRef.update(data)
})
.catch(err => console.log(err) )
});
but I can't get it to work on netlify lambda. Is there anyway I can use this function in netlify lambda?
You cannot deploy Firebase Cloud Functions to any other provider. Other environments might be totally different and may not have all the credentials/env variables required.
If you want to listen for realtime updates outside of GCP, you can try using Firestore's onSnapshot() but you'll need a server that runs always. The listener will stop once you serverless functions terminates.

Firestore functions listCollections() only returning empty array

Here is my database...
I have the following code in firebase functions...
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.getCollections = functions.https.onCall(async (data, context) => {
const path = admin.firestore().collection('BusinessName').doc('employee');
const collections = await path.listCollections();
collections.forEach(collection => {
console.log('Found subcollection with id:', collection.id);
});
return({ collections: collections })
});
And the front end code...
let buttonClick = () => {
let getCollections = firebase.functions().httpsCallable('getCollections');
getCollections().then((res) => {
console.log(res);
})
}
There is two subcollections in this path. This function should return an array with the two test collections seen in the above image. However, it only returns an empty array.
and in the functions log...
I've tired different paths with different database structures, but the return is always an empty array. There must be something wrong with the node.js function, but it's right from firebase's docs. What do you think...?
If this issue is only occurring while using Emulators, my first suggestion would be to check your Emulator Firestore Database. Is it empty? Did you create the necessary dummy data?
I'm saying this because your database screenshot is a LIVE database, and the Emulator doesn't touch that, it queries the Emulator db, typically located in: http://localhost:4000/firestore

firestore cloud functions not triggering

I am new to firebase cloud functions. So, I followed the tutorial in firebase youtube channel.
So, I created a function that should trigger when firestore document added,but it didn't trigger.
this is the function
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.whenAddData = functions.firestore
.document("chats/{userId}")
.onCreate((change, context) => {
const msg = change.data().msg;
const modifiedMsg = addImoji(msg);
console.log("data changing");
return change.ref({ msg: modifiedMsg });
});
const addImoji = (msg) => {
return msg.replace(/\bPizza\b/g, " 🍕 ");
};
firebase-functions version: "^3.6.1"
firestore db screenshot
First of all, your regex is wrong. It's case sensitive, which means the message from your screenshot "i love pizza" doesn't match "Pizza". To make it case insensitive (and thus match "Pizza", "pizza", "piZZA" ...) add the i flag at the end:
const addImoji = (msg) => {
return msg.replace(/\bpizza\b/gi, "🍕");
};
Secondly, your function returns a database reference. It doesn't actually store the new data by calling set() or update(). Your code should be:
return change.ref.update({ msg: modifiedMsg });
Any async Firebase function should return a promise (and update() returns a promise). If it doesn't, the function won't terminate correctly.
By returning the result of update, your function will keep running until the asynchronous work of writing the new msg to the database is completed.

Error Deploying Firebase function

I am trying to deploy a firebase cloud function that will push something to my algolia search engine everytime a new event is added under the events node. I followed the tutorial here which seems to detail how to do things for the most part.
https://www.youtube.com/watch?v=Njtbo3YUdH4
However, when I run my project i get the strangest error
Error occurred while parsing your function triggers.
TypeError: Cannot read property 'config' of undefined
I have never seen this error when trying to deploy functions in the past. Im not sure if something changed or not but I can't really find where to fix this error on firebase docs or stackoverflow so far.
I am running node version v8.11.3 in addition to that I am pretty sure that I have my algolia configured properly due to the fact that when I run
$ firebase functions:config:get
I get this
{
"algolia": {
"appid": "xxxxxxx",
"adminkey": "xxxxxxxxxx"
}
}
The only thing it could possibly be is my code. I will include it below if anyone could help me fix it I would greatly appreciate it.
//similar to import functions in swift
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
//exports acts as a global variable that you can init other properties on
//on
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
const algoliasearch = require('algoliasearch');
const algolia = algoliasearch(functions.config().algolia.appid,functions.algolia.config().adminKey)
exports.updateIndex = functions.database.ref('/events/{eventKey}').onWrite(event =>{
const index = algolia.initIndex('events');
const eventKey = event.params.eventKey
const data = event.data.val();
if(!data){
return index.deleteObject(eventKey,(err) =>{
if (err) throw err
console.log('Event deleted from algolia index',eventKey)
})
}
data['objectID'] = eventKey
return index.saveObject(data,(err,content) =>{
if (err) throw err
console.log('Event updated in algolia index',data.objectID)
})
});
Look at this line (I added a carriage return):
const algolia = algoliasearch(functions.config().algolia.appid,
functions.algolia.config().adminKey)
This looks correct:
functions.config().algolia.appid
This doesn't:
functions.algolia.config().adminKey
It looks like you meant to say this instead:
functions.config().algolia.adminKey

Resources