I've been trying to send a notfication to topic "All" and the console log shows error:
Notification sent failed: TypeError: admin.messaging is not a function
Code:
// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
var admin = require("firebase-admin/app");
const { applicationDefault } = require('firebase-admin/app');
admin.initializeApp({
credential: applicationDefault(),
databaseURL: "my-firebase-url"
});
exports.notificationsOnCreate = functions.database.ref("/{type}/{id}/").onCreate(async (snapshot, context) => {
const payload = {
notification: {
title: 'cloud function demo',
body: 'this is a test notification'
}
};
try{
return await admin.messaging().sendToTopic("All", payload)
.then(function(response){
console.log('Notification sent successfully: ', response);
});
} catch(err) {
console.log('Notification sent failed: ', (err));
}
})
Other stack overflow topics recommend updating firebase-admin to a version >5.1, but that seems to not be the issue here.
package.json file:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^11.3.0",
"firebase-functions": "^4.1.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
CodePudding user response:
import from firebase-admin
instead of firebase-admin/app
// The Firebase Admin SDK to access Firestore.
var admin = require("firebase-admin");