我正在使用firebasecloud函数,我想在firebaseDB中添加产品时发送通知。为了做到这一点,我正在从消防商店获取设备令牌。然而,当我运行firebase deploy时,我会收到以下错误消息:
error Parsing error: Unexpected token db
这是index.js中的代码
/* eslint-disable */
const functions = require("firebase-functions");
const admin = require('firebase-admin');
const db = admin.firestore();
exports.sendToDevice = functions.database
.ref('products/{productId}')
.onCreate((snapshot, context) => {
// const product = snapshot.val();
const querySnapshot = await db
.collection('users')
.doc('abcdefgh1235678')
.collection('tokens')
.get();
const tokens = querySnapshot.docs.map(snap => snap.id);
admin.messaging().sendToDevice(tokens,{
notification: {
title: 'New Product!',
body: `New product is ${context.params.productId}`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
});
return;
});
更新我的答案后,我得到了以下错误:
error分析错误:意外的令牌=>
/* eslint-disable */
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.printitemcreated = functions.database.ref('/products/{productId}')
.onCreate(async(snapshot, context) => {
const original = snapshot.val();
const querySnapshot = await db
.collection('users')
.doc('abcdefg123456')
.collection('tokens')
.get();
const tokens = querySnapshot.docs.map(snap => snap.id);
await admin.messaging().sendToDevice(tokens,{
notification: {
title: 'New Product!',
body: `New product is ${context.params.productId}`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
});
return;
});
AFAIKdb
不是云函数的保留关键字。
问题很可能来自于您没有初始化管理应用程序实例的事实。你应该做admin.initializeApp();
。
此外,您的Cloud函数还包含其他(关键(错误:您使用await
时没有将处理程序声明为async
,也没有等待对admin.messaging()
的调用。
以下代码应该有效:
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp(); // <- See here
const db = admin.firestore();
exports.sendToDevice = functions.database
.ref('products/{productId}')
.onCreate(async (snapshot, context) => { // <- See async here
// const product = snapshot.val();
const querySnapshot = await db
.collection('users')
.doc('abcdefgh1235678')
.collection('tokens')
.get();
const tokens = querySnapshot.docs.map(snap => snap.id);
await admin.messaging().sendToDevice(tokens,{ // <- See await here
notification: {
title: 'New Product!',
body: `New product is ${context.params.productId}`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
});
return null; // <- See null here
});