Firebase cloud function always timeout - javascript

I'm exploring the firebase cloud functions and I'm trying to send a notifications with an http request.
The problem is that even if I manage to send the notification, the request always goes timeout.
Here's my script
/functions/index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.friendRequestNotification = functions.https.onRequest((req, res) => {
const senderId = req.query.senderId;
const recipientId = req.query.recipientId;
const getRecipientPromise = admin.database().ref(`/players/${recipientId}`).once('value');
const getSenderPromise = admin.database().ref(`/players/${senderId}`).once('value');
return Promise.all([getRecipientPromise, getSenderPromise]).then(results => {
const recipient = results[0];
const sender = results[1];
const recipientToken = recipient.child("notificationsInfo/fcmToken").val();
const notificationAuthorization = recipient.child("notificationsInfo/wantsToReceiveNotifications").val();
const recipientBadge = recipient.child("notificationsInfo/badgeNumber").val();
const senderUsername = sender.child("username").val();
const payload = {
notification: {
title: `FriendRequest`,
body: `You have a new friend request from ${senderUsername}!`,
badge: (recipientBadge+1).toString()
}
};
if (notificationAuthorization) {
return admin.messaging().sendToDevice(recipientToken, payload).then(response => {
});
}
return admin.database().ref(`/players/${recipientId}/notificationsInfo/badgeNumber`).setValue(recipientBadge+1);
});
});
Plus It seems that the badgeNumber in never updated, is that related to the timeout issue?

HTTP-triggered Cloud Functions work just like Express apps -- you have a response object (res) that you need to use to send something when the request is done. In this case, it looks like you could do something like:
return Promise.all([
/* ... */
]).then(() => {
res.status(200).send('ok');
}).catch(err => {
console.log(err.stack);
res.status(500).send('error');
});

#Michael Bleigh answer is perfectly fine for this question, let me add more in this for the future users.
As per firebase documentation:-
Use these recommended approaches to manage the lifecycle of your
functions:
Resolve functions that perform asynchronous processing (also known as
"background functions") by returning a JavaScript promise.
Terminate HTTP functions with res.redirect(), res.send(), or res.end(). (The case in this question.)
Terminate a synchronous function with a return; statement.
Note
It's important to manage the lifecycle of a function to ensure that it resolves properly. By terminating functions correctly, you can avoid excessive charges from functions that run for too long or loop infinitely. Also, you can make sure that the Cloud Functions instance running your function does not shut down before your function successfully reaches its terminating condition or state.
You need a paid plan (Blaze, pay as you go) to access external APIs.
You might see below warning in firebase functions log if the billing account is not configured.
Billing account not configured. External network is not accessible and
quotas are severely limited. Configure billing account to remove these
restrictions
Check this link for more information.

Related

Sending FCM messages to web apps through firebase cloud functions

Is it possible to send FCM notifications through Firebase Cloud Functions, when a Firestore data field changes, but for a website, not an app. There is lots of guidance out there for Android and iOS but nothing for simply web apps, outside of sending notifications from the Firebase Console).
I've been trying to find out how to trigger a notification from Cloud Functions but can't find anything useful.
As an example, my database has the following structure:
Collection: users
Documents: documents named using userID
Data Fields: Fields 1 through 5. Field 5 stores the FCM Token. Field 1 stores their status (online, offline, offline pending messages).
I would like to ensure that when Data Field 1 changes (to 'offline pending messages), that the relevant user gets notified (based on the Doc ID).
Edit: adding code below for reference
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/users/{doc}/{Hears}')
.onUpdate(async (change, context) => {
const db = admin.firestore();
db.collection('users').doc(context.params.userId) // get userId
.get()
.then(doc => {
//this is intended to get the FCM token stored in the user's document
const fcmToken = doc.data().usrTkn;
// Notification details
const payload = {
notification: {
title: 'You have a new message.',
body: 'Open your app'
}
};
})
//This should send a notification to the user's device when web app is not in focus.
//FCM is set up in service worker
const response = await admin.messaging().sendToDevice(fcmToken, payload);
console.log(response);
});
Sending messages to a web app is no different from sending it to a native mobile app, so the sending part of guidance you've found is equally applicable. The Firebase documentation even contains an example of sending notifications on a Realtime Database trigger, and doing the same for Firestore would not be much different.
If you're having a specific problem sending messages, I recommend showing what you tried, and what isn't working about it.
Update: your code doesn't work (no matter what sort of device you send the notification to), because you're not handling the asynchronous nature of get() in your code.
The simplest way to fix that is to use await there too, just like you do when calling sendToDevice. So:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/users/{doc}/{Hears}')
.onUpdate(async (change, context) => {
const db = admin.firestore();
const doc = await db.collection('users').doc(context.params.userId).get();
const fcmToken = doc.data().usrTkn;
const payload = {
notification: {
title: 'You have a new message.',
body: 'Open your app'
}
};
const response = await admin.messaging().sendToDevice(fcmToken, payload);
console.log(response);
})
I highly recommend spending some time on learning about asynchronous calls, closures, async/await, and how to debug something like this by adding logging.

sending push notification using firebase functions every time a new child is added in firebase realtime database is not working

I am trying to send a push notification every time a child is created with no success.
I am creating a child with 2 token names with a question mark between them and trying to send to those tokens the notification.
to get the tokens from the phones I am using
new FirebaseMessaging().getToken() .
here is the firebase functions code
`
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
exports.onNewMessage = functions.database.
ref('/messages/{pushId}')
.onCreate((snapShot,context)=>{
var str = snapShot.key();
var res = str.split("?");
// Notification details.
const payload = {
notification: {
title: 'title!',
body: `body!`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
// Send notifications to all tokens.
admin.messaging().sendToDevice(res[0], payload);
admin.messaging().sendToDevice(res[1], payload);
});` .
This may have many if-thens, but I will describe here the most common sources of errors
1) Did not grant permissions for notifications for iOS/Android platform. For Android it is fine, and relatively easy to receive notifications, but for iOS you need Developer account to do that (on December 2019 it was 99$ per year)
2) I would recommend using topic subscription instead of tokenization (i.e. .getToken()) as it removes burden of following every single sent message manually
For example:
final fbmsg = FirebaseMessaging();
fbmsg.requestNotificationPermissions();
fbmsg.configure(onMessage: (msg) {
print(msg);
return;
}, onLaunch: (msg) {
print(msg);
return;
}, onResume: (msg) {
print(msg);
return;
});
fbmsg.subscribeToTopic('chats');
You can configure onLaunch, onResume, and onMessage behaviors on your own demand
For (1) and (2), a great place to start is following documentation of firebase_messaging library
3) I am not sure about this, but I think a better way to use index.js file could be using the snapshot that you receive (or at least try console.log() of whatever you get to check validity). But if it works for you, just ignore this step :) Below I attach the code from my app with working notifications
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.myFunction = functions.firestore
.document('chats/{message}')
.onCreate((snapshot, context) => {
return admin.messaging().sendToTopic('chats', {
notification: {
title: snapshot.data().username,
body: snapshot.data().text,
clickAction: 'FLUTTER_NOTIFICATION_CLICK'
},
});
});
4) I had hard time with establishing this Firebase Functions feature, also check installation steps for them as well
5) Check how you are trying to send the notification, first try to simulate it from the console, make sure that receiving part works, and then try to create an automated one
Hope it helped!

Firebase: Calling Cloud Function From Cloud Function

I am running in to an issue with Firebase cloud functions. I have an onWrite cloud function that triggers a sequence of events. I have a path for requests that the onWrite cloud function is tied to. When that cloud function executes, it deletes the new request for the requests path and pushes the request in to a render path/que that will be used client side for rendering UI elements/data. Once the data has been written to the render path, I call a vanilla javascript function that is not tied to any cloud events. The vanilla javascript function is supposed to reach out to an external API and fetch some data to later be updated on the render object that was pushed in to the render path.
The problem is that the vanilla javascript function never executes. I have been looking all over the web to figure out why this happening but can't seem to figure out why. I am on the Flame plan so outbound api requests should be allowed to my knowledge. Here an example of my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request');
admin.initializeApp();
exports.requestModule = functions.database.ref('/requests').onWrite((change, context) => {
// Create reference to database
let db = admin.database();
if (context && context.auth && context.auth.uid) {
const afterData = change.after.val();
let uid = context.auth.uid;
let cleanData = afterData[uid];
cleanData.status = "loading";
// Remove the requested module from the requests path
let cleansePath = db.ref('/requests/' + uid);
cleansePath.remove().then((snapshot) => {
return true;
}).catch((error) => {
console.log(error);
return false;
});
// Add requested module to the render path
let renderPath = db.ref('/render/' + uid);
renderPath.push(cleanData).then((snapshot) => {
let val = snapshot.val();
let key = snapshot.key;
// Trigger the get weather api call
getWeather(uid, key, val);
return true;
}).catch((error) => {
console.log(error);
return false;
});
}
});
// Fetches data from external api
function getWeather (uid, key, obj) {
console.log('Fetching weather!');
let db = admin.database();
request('https://api.someweathersite.net/forecast/', (error, response, body) => {
if (!error && Number(response.statusCode) === 200) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
obj.data = body;
obj.status = 'loaded';
// Set data from api response in render object to be shown client side
let render = db.ref('/render/' + uid + '/' + key );
render.set(obj).then(() => {
return true;
}).catch((error) => {
console.log(error)
return false;
});
}
});
}
The console.log message at the top of the "getWeather" function never executes. I don't think that the "getWeather" function is ever executing.
If I put the api call directly in the onWrite "requestModule" function, the api call will work. However, when it calls an external function it never gets called/works. I basically want to have the "requestModule" function handle all requests and plan to have a module dispatcher that handles which module function/api data should be fetched from. That's why I don't want to keep the api call in the "requestModule" function. Any idea of why this happening or how I can get this working?
getWeather is performing asynchronous work to fetch some data, but it's not returning a promise to indicate when that work is complete. In fact, none of the async work you're performing here is correctly using the promises returned by the various API calls. It's not sufficient to simply use then() on each promise.
You need to keep track of all of the async work, and return a single promise that resolves only after all the work is complete. Otherwise, Cloud Functions may terminate and clean up your function before the work is complete. (Note that it's not deterministic which work may or may not actually complete before forced termination, but the only way to ensure that all work completes is through that single promise you return.)
You may want to watch my tutorials on using promises in Cloud Functions to get a better handle on what you're required to do make your functions work correctly: https://firebase.google.com/docs/functions/video-series/

How to write a cloud function for firebase that will change data based on time

My firebase database structure looks like this:
-events
-uniqueEventId
-endTimeStamp: 1507949100
-active: true
-uniqueEventId2
-endTimeStamp: 1807949100
-active: true
-uniqueEventId3
-endTimeStamp: 1900949100
-active: true
How do I cloud function which can get all the events with timestamps before the current time and set their active to false.
I'm not sure how you want Cloud Functions to be triggered in this case. I'll assume you want a HTTP trigger, so that you can simply call it from the browser or a web hook.
That means you start with a basic HTTP-triggered function:
exports.updateStatus = functions.https.onRequest((req, res) => {
// ...
res.status(200).send("done");
});
Next up you'll need to access the Realtime Database within this function. To do that you'll use the Firebase Admin SDK, which gives you easy administrative access within your code:
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateStatus = functions.https.onRequest((req, res) => {
// ...
res.status(200).send("done");
});
Then we get to the actual code to change the data. This is standard database access code and has little to do with Cloud Functions. In this case you want to query for timestamp, loop over the results, and set the active property:
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateStatus = functions.https.onRequest((req, res) => {
let now = Date.now();
let query = admin.database().ref("events").orderByChild("timestamp").startAt(now);
query.once("value").then(function(snapshot) {
var promises = [];
snapshot.forEach(function(child) {
promises.push(child.ref.update({ active: false }));
})
Promise.all(promises).then(function() {
res.status(200).send("done");
});
});
});
That last code is a bit tricky, since it deals with many asynchronous write operations. Cloud Functions will terminate your function after your send the response to the client, so it's important that you only send a response back after all those asynchronous writes are done. I use a Promise.all() for that. For more information on this asynchronous nature, read the documentation, this blog post, and watch this video.
For more info, I'd recommend studying the documentation for the Firebase Admin SDK.

Dangling callbacks: return response before every callback has returned

Question: Would you consider dangling callbacks as bad node.js style or even dangerous? If so under which premise?
Case: as described below, imagine you need to make calls to a DB in an express server that updates some data. Yet the client doesn't need to be informed about the result. In this case you could return a response immediately, not waiting for the asynchronous call to complete. This would be described as dangling callback for lack of a better name.
Why is this interesting?: Because tutorials and documentation in most cases show the case of waiting, in worst cases teaching callback hell. Recall your first experiences with say express, mongodb and passport.
Example:
'use strict'
const assert = require('assert')
const express = require('express')
const app = express()
function longOperation (value, cb) {
// might fail and: return cb(err) ...here
setTimeout(() => {
// after some time invokes the callback
return cb(null, value)
}, 4000)
}
app.get('/ping', function (req, res) {
// do some declartions here
//
// do some request processesing here
// call a long op, such as a DB call here.
// however the client does not need to be
// informed about the result of the operation
longOperation(1, (err, val) => {
assert(!err)
assert(val === 1)
console.log('...fired callback here though')
return
})
console.log('sending response here...')
return res.send('Hello!')
})
let server = app.listen(3000, function () {
console.log('Starting test:')
})
Yeah, this is basically what called a "fire and forget" service in other contexts, and could also be the first step in a good design implementing command-query response separation.
I don't consider it a "dangling callback", the response in this case acknowledges that the request was received. Your best bet here would be to make sure your response includes some kind of hypermedia that lets clients get the status of their request later, and if it's an error they can fix have the content at the new resource URL tell them how.
Think of it in the case of a user registration workflow where the user has to be approved by an admin, or has to confirm their email before getting access.

Categories

Resources