Junaid Bashir
Junaid Bashir

Reputation: 172

Issue with initializeApp() in firebase functions

i am getting warnings in firebase cloud functions log. the functions were deployed properly and was working before. now i am getting an error.

@firebase/database: FIREBASE WARNING: Provided authentication credentials for the app named "[DEFAULT]" are invalid. This usually indicates your app was not initialized correctly. Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.

I have spent 5 to 6 hours for searching solution then i tried one solution in which i have downloaded the the serviceAccountKey.json file and use that file but the i got an other error while deploying the functions. and i didn't find any solution yet. here is the error

Error: Error occurred while parsing your function triggers.

ReferenceError: functions is not defined
    at Object.<anonymous> (D:\Parental Sheild\Coding\defenderFunctions\functions\index.js:22:25)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at C:\Users\H.A.R\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:18:11
    at Object.<anonymous> (C:\Users\H.A.R\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:38:3)

i have upgrade node to 8.12.0 and upgrade npm to latest version.

here the code of initializing App

const functions = require('firebase-functions');

const admin = require("firebase-admin");

const serviceAccount = require("./serviceAccountKey.json");

admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "https://database url"
});

here is my firebase function code

exports.sendMessage = functions.database.ref('/Defender/{UserId}/Child/{PinId}/Messages/{pushId}')
    .onWrite((change,context) => {
        const message = change.after.val();
        const sender = message.from;
        const receiver = message.to;
        const userID= message.uid;
        const promises = [];

        // if (senderUid == receiverUid) {
        //     //if sender is receiver, don't send notification
        //     promises.push(change.after.ref.remove());
        //     return Promise.all(promises);
        // }

        if (userID== receiver) {

                 const getInstanceIdPromise = admin.database().ref(`/Defender/${userID}/Profile/instanceId`).once('value');
                 const getSenderUidPromise = admin.database().ref(`/Defender/${userID}/Child/${sender}/Profile/name`).once('value');

            return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(results => {
            const instanceId = results[0].val();
            const sender = results[1].val();
            console.log('notifying ' + receiver + ' about ' + message.body + ' from ' + sender);

            const payload = {
                notification: {
                    title: sender,
                    body: message.body,
                    sound: "default"
                    // icon: sender.photoURL
                }
            };

            admin.messaging().sendToDevice(instanceId, payload)
                .then(function (response) {
                    console.log("Successfully sent message:", response);
                })
                .catch(function (error) {
                    console.log("Error sending message:", error);
                });
        });

        }else{

                 const getInstanceIdPromise = admin.database().ref(`/Defender/${userID}/Child/${receiver}/Profile/instanceId`).once('value');
                 const getSenderUidPromise = admin.database().ref(`/Defender/${userID}/Profile/displayName`).once('value');

            return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(results => {
            const instanceId = results[0].val();
            const sender = results[1].val();
            console.log('notifying ' + receiver + ' about ' + message.body + ' from ' + sender);

            const payload = {
                notification: {
                    title: sender,
                    body: message.body,
                    sound: "default"
                    // icon: sender.photoURL
                }
            };

            admin.messaging().sendToDevice(instanceId, payload)
                .then(function (response) {
                    console.log("Successfully sent message:", response);
                })
                .catch(function (error) {
                    console.log("Error sending message:", error);
                });
            });

        }

    });

Update: i have found the issue. i am reading data from database inside the function and getting error because i have secure rules on my firebase database. now i don't know how to solve this issue. any help?

Upvotes: 3

Views: 2984

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317657

You're using functions, but you never apparently never defined it in your code. You probably meant to require the firebase-functions at the top of your code:

const functions = require('firebase-functions')

Upvotes: 1

Related Questions