The docs for firebase functions v2 includes information on how to listen to published messages however it doesn't show how to publish messages.
exports.hellopubsub = onMessagePublished("topic-name", (event) => {
// ...
});
How do you publish messages from v2 pubsub functions without starting a separate nodejs server?
Related
Well, I'm really lost here so any help would be great. My app works with a DOTNET6 API backend and a Vue3 frontend.
I'm registering users via Google Sign In directly from my frontend (Vue3) with this code:
async googleLogIn() {
const provider = new GoogleAuthProvider;
var gUser;
await signInWithPopup(getAuth(), provider)
.then((result) => {
gUser = result.user;
console.log(gUser);
})
.catch((error) => {
console.log(error);
});
}
The user gets correctly saved in Firebase, and that should be all. The thing is, even though I'm not interacting with my DOTNET API, said API gets shut down without specifying the error. The message displayed in VS Debug Console is : ...\my_api.exe (process 32400) exited with code -1.
I believe the ports used by my API might be the problem (already tried changing them but it keeps failing), but I don't understand why the Google Sign In would interfere with my local API.
I am using FCM for notification. FCM gets triggered on creation of data from the Firebase database. I received first message. After that other consecutive messages is not received. I'm running this in a local environment. Is the problem due to the below message "Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions" or any other issue. Do I need to get into a billing plan for receiving messages. Working in test environment and that is the reason not moving to billing plan. If the issue is not related to billing plan can someone point any other problem with the code.
Firebase function log
6:22:52.133 PM
sendFollowerNotification
Function execution started
6:22:52.133 PM
sendFollowerNotification
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
6:22:52.143 PM
sendFollowerNotification
Function execution took 10 ms, finished with status: 'ok'
6:22:52.401 PM
sendFollowerNotification
1 messages were sent successfully
Node js code
exports.sendFollowerNotification = functions.database.ref('/notification/message/{gId}/{pId}')
.onCreate(async (change, context) => {
//console.log('Group id:', context.params.gId," Push ID:",context.params.pId, "Change",change);
const notificationData = change.val();
var topic = notificationData.topic;
var title = notificationData.title;
var body = notificationData.body;
var registrationTokens = notificationData.tokens;
const message = {
notification: {
title: title,
body: body
},
tokens: registrationTokens,
};
admin.messaging().sendMulticast(message)
.then((response) => {
// Response is a message ID string.
console.log(response.successCount + ' messages were sent successfully');
})
.catch((error) => {
console.log('Error sending message:', error);
});
});
That message does not indicate an error. It's just a warning letting you know that outbound networking does not work if your project is not on a payment plan. FCM messaging does not fall in this category - it should work.
The problem is that your code doesn't return a promise that resolves after all asynchronous work is complete. Right now, it returns nothing, and the function terminates immediately before the message is sent. Please read and understand the documentation about this.
Minimally, you will need to return the promise chain to let Cloud Functions know when the message is sent, and it's safe to terminate.
return admin.messaging().sendMulticast(message)
.then((response) => {
// Response is a message ID string.
console.log(response.successCount + ' messages were sent successfully');
})
.catch((error) => {
console.log('Error sending message:', error);
});
Note the return keyword above.
If the message still isn't being sent, then there is some other problem here that we can't see. You might not be handling your device tokens correctly.
I think this might answer your question: Why will I need a billing account to use Node.js 10 or later for Cloud Functions for Firebase?:
Because of updates to its underlying architecture planned for August 17, 2020, Cloud Functions for Firebase will rely on some additional paid Google services: Cloud Build, Container Registry, and Cloud Storage. These architecture updates will apply for functions deployed to the Node.js 10 runtime. Usage of these services will be billed in addition to existing pricing.
In the new architecture, Cloud Build supports the deployment of functions. You'll be billed only for the computing time required to build a function's runtime container.
On the other hand, the Service Firebase Clud Messaging itself is free:
Firebase Cloud Messaging (FCM) provides a reliable and battery-efficient connection between your server and devices that allows you to deliver and receive messages and notifications on iOS, Android, and the web at no cost.
Given that you are using Node in your CFs, the Platform requires to you a Billing Account.
In the official documentation of Firebase, we can do it with https://firebase.google.com/docs/firestore/query-data/listen
let doc = db.collection('cities').doc('SF');
let observer = doc.onSnapshot(docSnapshot => {
console.log(`Received doc snapshot: ${docSnapshot}`);
// ...
}, err => {
console.log(`Encountered error: ${err}`);
});
But how can we do it with Google Apps Script?
To run an Apps Script on a event (like a data update) implies using triggers. Unfortunately, at the moment there are no Apps Script triggers supporting Firebase.
However, you can include JavaScript code in the HTML file attached to your Apps Script file and deploy it as a Web App.
I want my firebase backend to send an email to me when a document is created in a firestore collection based on a form submission in my vue app..
I found sendgrid to be the easiest to get the job done, the example mentioned in the package page suggests that I store the API key in an Environment variable.
Since this will run from a cloud function, I used the following command firebase functions:config:set sendGrid.key="THE API GOES HERE" as mentioned in Firebase docs here
cloud function
I initialized the firebase cloud functions locally, then I called the admin module so i can listen to onCreate() when a document is created in firestore,
I used sendGrid inside the callback function of onCreate()..
I tested the code and checked the functions logs in my firebase project and it gets invoked and finished successfully with a status ok, which means that everything should be working fine.
here is my index.js code inside the /functions folder in my project root
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// sendGrid
const sgMail = require('#sendgrid/mail');
// the cloud function
exports.formSubmitted = functions.firestore.document('message/{messageId}').onCreate(doc => {
// referencing the form data
const formData = doc.data();
// the following should be logged in the function logs in my firebase project
console.log(formData);
// retrieving the environment variable
sgMail.setApiKey(functions.config().sendgrid.key);
// the message to be sent
const msg = {
to: 'MY-EMAIL#gmail.com',
from: formData.email,
subject: 'new user submitted our contact form',
text: formData.message,
html: '<h3> test email from sendGrid </h3>'
}
return sgMail.send(msg);
})
result:
everything worked fine except I didn't receive the email.
If further code/explanation is needed, please leave a comment below.
any help or hints is highly appreciated, thanks in advance.
I'm trying to use Firebase functions as our server. Here's the function I'm using. It works fine when I trigger it over HTTP
exports.subscriptions = functions.https.onRequest((request, response) => {
// Send 200 code to the server indicate to that you are done!
response.send(200);
});
Apple Says:
The App Store will deliver JSON objects via an HTTP POST to your
server for the key subscription
But so far I didn't get any notification from Apple server.
Any suggestions would be great?
I checked the logs in the console and it seems that I have started receiving notifications from Apple server.
well you're only saying to apple that you're done, if you add console.log(req.body) to your function it should give you some data in the logs :)