Firebase Cloud Functions - Error: handler is not a function at cloudFunction - node.js

I'm trying to notify every user subscribed to a topic in the app once a part of my database is updated. I uploaded the following cloud function:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.PushNotification =
functions.firestore.document("/Alert_places/{alert}").onCreate(
(snapshot, context) =>
{
admin.messaging().sendToTopic("helper",{
notification: {
title: "MyApp",
body: "Body"
}
}
)
}
);
The function uploaded fine, but following an event I get the following messages on the logs:
So no user gets the notification.

Related

cloud functions: trying to create user on firestore from cloud functions "failed to deploy"

I am trying to access my db upon http request.
in the api builder from google i use node.js 16 as a runtime.
I tried running this code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firestore);
const firestoreDB = admin.firestore()
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase Cloud Functions!");
console.log("function triggered")
});
exports.createUser = functions.firestore.document('Users/asddsa')
.onCreate((snap, context) => {
const newValue = snap.data();
if (snap.data() === null) return null;
const uid = context.params.userId
let notificationCollectionRef = firestoreDB.collection('Users').doc(uid).collection('Notifications')
return notificationCollectionRef.add({
notification: 'Hello Notification',
notificationType: 'Welcome'
}).then(ref => {
return console.log('notification successful', ref.id)
})
});
But I cant even deploy it, it just states that "deployment failed".
Now this is usually when there is a typo in the code. But I am guessing that I didnt set up the connection to the firestore properley. (I never gave it a password or anything)
I assumed that as it is inside the same project, the connection would work either way, but maybe I am wrong?
How do I set up the connection to create the user and not have the deployment fail?
The instructions for Initial setup to configure and set up your Cloud Functions for Firebase project. you can check the Firebase documentation.
You can check the details in Cloud firestore trigger. Which describes Event triggers where you can trigger a function to fire any time a new document is created in a collection by using an onCreate(). This function calls createUser every time a new user profile is added.
Also You can have a look at Github link to create the user.

Error trying to authenticate with FCM servers when sending message using Firebase Admin SDK in node.js

When I try to send to send an FCM notification to a topic I get the following error...
Error: An error occurred when trying to authenticate to the FCM
servers. Make sure the credential used to authenticate this SDK has
the proper permissions.
I am using a brand new generated service account key and pointing to it correctly. I have confirmed that the path to the key is correct. I have also enabled Cloud Messaging for the project.
const { messaging } = require('firebase-admin');
var admin = require('firebase-admin');
console.log(process.cwd());
async function run() {
try {
var serviceAccount = require("/Users/myUser/src/my_project/node_admin/my_project-5617a-firebase-adminsdk-lwpk6-5dad9000e0.json");
const topic = 'all';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const payload = {
notification: {
title: "Test1234",
body: "body",
sound: 'test-sound.wav'
}
};
var options = {
priority: "high"
}
await admin.messaging().sendToTopic(topic , payload , options);
} catch (e) {
console.log(e);
}
}
run();
Hello i was copy code and run --> it working
so i think you can check path of file auth json
var serviceAccount = require("/Users/myUser/src/my_project/node_admin/my_project-5617a-firebase-adminsdk-lwpk6-5dad9000e0.json");
good luck!

Problems deploying firebase functions

I am trying to use firebase functions in reactjs to create a trigger that sends a mail when information is uploaded to the firestore database.
A bridge is created with nodemailer and a function is executed when a new document is loaded into the db.
This is the code:
const functions = require("firebase-functions");
const nodemailer = require("nodemailer");
/* const admin = require('firebase-admin');
admin.initializeApp(); */
// GmailAccount
const gmailUser = "myname#gmail.com"; //example mail, use another
const gmailPassword = "mypass"; //example pass, it is not the real one that I use.
const transport = nodemailer.createTransport({
service: "gmail",
auth: {
user: gmailUser,
pass: gmailPassword
}
});
exports.newContact = functions.firestore
.document("/Contacts/{documentId}")
.onCreate((snap, contentxt) => {
const name = snap.data().name;
return sendEmail(name);
});
const sendEmail = (name) => {
return transport
.sendMail({
from: gmailUser,
to: "myEmail#gmail.com",
subject: "test",
html:name
})
.then(r => console.log(r))
.catch(e => console.log(e));
}
So far so good. The problem occurs when I want to deploy: I execute the command:
firebase deploy --only functions and the console gives me the following:
Functions deploy had errors with the following functions:
newContact(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
A more detailed error would be the following:
{"code":3,"message":"Function failed on loading user code.
When running: firebase emulators:start --only functions
It tells me: function ignored because the firestore emulator does not exist or is not running

flutter: how to show different notifications content based on chosen topic using firebase functions in my node.js

in my app the user gets to choose the language of the app based on a specific button that holds the string of the language name. i wanna send notifications to them according to the language they chose to operate the app with. how do i do that with cloud functions if i subscribe the user to a different language topic based on their choice of language?
heres my current index.js code for firebase functions that subscribes to only one topic which is sending notifications in english only:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var newData;
exports.messageTrigger = functions.firestore.document('messages/{messagesId}').onCreate(async (snapshot, context) => {
newData = snapshot.data();
const payload = {
notification: {
title: newData.message,
body: newData.body,
},
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
message: newData.message,
}
};
admin.messaging().sendToTopic('messages', payload);
});

Firebase function not responding to Pub/Sub message

I feel like I might be missing something simple, but I can't get a Cloud Function for Firebase to respond to a Pub/Sub published message. It works fine when I deploy using cloud and opt for the Admin SDK for Node.js, but Auth is tricky; it works for the first write and then it fails to authenticate.
With the release of Cloud Function for Firebase, I decided to try again. My function code is as follows:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
function pushOrderToFirebase(completedOrder) {
admin.initializeApp(functions.config().firebase);
//setters and getters for the message that will be pushed to firebase
admin.database().ref('/orders').push({
name: curDriverName,
recipient: recipient,
address: address,
details: details,
isDelivered: isDelivered,
failureReason: failureReason,
time: formattedTime
}).then(snapshot => {
console.log(snapshot);
});
}
exports.firebasePusherAlpha = functions.pubsub.topic('test-topic').onPublish(event => {
const pubSubMessage = event.data;
let parsedMessage = null;
try {
parsedMessage = pubSubMessage.json;
console.log(parsedMessage);
} catch (e) {
console.error('PubSub message was not JSON', e);
}
pushOrderToFirebase(parsedMessage);
callback();
});
Unfortunately, it doesn't get called when I publish a pubsub message.

Resources