我已经更新了问题,找到了问题的根本原因。
因为我托管了我的React SSR应用程序,它在客户端使用firebase数据库,由一个名为
app
抛出错误
Error: FIREBASE FATAL ERROR: Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.
. 当我一个接一个地评论和部署时,工作得很好。但当我一起部署的时候不行。我如何将这两个分开,使它们保持在同一回购协议中?
原题:
Why firebase cloud function throwing an error of 'The default Firebase app does not exist.'?
所以我第一次尝试firebase函数。admin.messaging()引发以下错误。帮我找出原因?
如果我看一下控制台,我会得到结果,直到
console.log('deviceToken', deviceToken);
那有什么不对的
const messageDone = await admin.messaging().sendToDevice(deviceToken, payload);
?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.updateUnreadCount = functions.database.ref('/chats/{chatId}/{messageId}')
.onCreate(async(snap, context) => {
const appOptions = JSON.parse(process.env.FIREBASE_CONFIG);
appOptions.databaseAuthVariableOverride = context.auth;
const adminApp = admin.initializeApp(appOptions, 'app');
const { message, senderId, receiverUid } = snap.val();
console.log(message, senderId, receiverUid);
console.log('------------------------');
const deleteApp = () => adminApp.delete().catch(() => null);
try {
const db = adminApp.database();
const reciverUserRef = await db.ref(`users/${receiverUid}/contacts/${senderId}/`);
console.log('reciverUserRef', reciverUserRef);
const deviceTokenSnapshot = await reciverUserRef.child('deviceToken').once('value');
const deviceToken = await deviceTokenSnapshot.val();
console.log('deviceToken', deviceToken);
const payload = {
notification: {
title: 'Test Notification Title',
body: message,
sound: 'default',
badge: '1'
}
};
const messageDone = await admin.messaging().sendToDevice(deviceToken, payload);
console.log('Successfully sent message: ', JSON.stringify(messageDone));
return deleteApp().then(() => res);
} catch (err) {
console.log('error', err);
return deleteApp().then(() => Promise.reject(err));
}
});
更新1:根据此
https://firebase.google.com/docs/cloud-messaging/send-message#send_to_a_topic
,
admin.messaging().sendToDevice(deviceToken, payload)
API仅在Admin Node.js SDK中可用?
所以改成
const payload = {
data: {
title: 'Test Notification Title',
body: message,
sound: 'default',
badge: '1'
},
token: deviceToken
};
const messageDone = await admin.messaging().send(payload);
也不管用。得到一个错误
Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
任何线索都有帮助。
编辑:终于使函数工作了。
我的index.js正在导出到函数,如下所示
exports.app = functions.https.onRequest(app);
exports.updateChat = functions.database.ref('/chats/{chatId}/{messageId}').onCreate(updateChat);
exports.app
是一个react ssr函数,我用它来托管我的站点。这也使用数据库。和投掷错误
multiple database instance
.
当我一个接一个地评论和部署时,工作得很好。但当我一起部署的时候不行。我如何将这两个分开,使它们保持在同一回购协议中?有什么建议吗?