Есть несколько пунктов, которые вы должны изменить в своей облачной функции:
1 / Вы должны активировать его при создании документа, как показано ниже.См. https://firebase.google.com/docs/functions/firestore-events?authuser=0#wildcards-parameters.
exports.sendNotifications = functions.firestore.document('Notifications/{notifId}')
.onCreate(async (snap, context) => {
const newValue = snap.data();
// perform desired operations ...
// You may not need the notifId value but you have to keep the wildcard in the document path
});
2 / Также обратите внимание, как onCreate()
имеет параметры data
и context
.См. https://firebase.google.com/docs/functions/firestore-events?authuser=0#trigger_a_function_when_a_new_document_is_created и https://firebase.google.com/docs/functions/beta-v1-diff?authuser=0#cloud-firestore для получения более подробной информации.
3 / Наконец, вы должны вернуть обещание, возвращаемое асинхронной задачей admin.messaging()
, а также вернуть значение в случае tokens.length = 0
.Эти два действия гарантируют, что вы указываете платформе, что работа облачной функции завершена.(Я бы посоветовал вам посмотреть 3 видео о «Обещаниях JavaScript» из серии видеороликов Firebase: https://firebase.google.com/docs/functions/video-series/)
Итак, в конце ваш код будет выглядеть следующим образом. (Обратите внимание, что яне проверял его, поэтому я не могу на 100% гарантировать, что он решит вашу проблему «Ошибка HTTP: 400, запрос содержит ошибки» ...)
exports.sendNotifications = functions.firestore.document('Notifications/{notifId}')
.onCreate(async (snap, context) => {
// Notification details.
const payload = {
notification: {
title: 'Hello',
body: 'Hello again',
click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
}
};
// Get the list of device tokens.
const allTokens = await admin.firestore().collection('fcmTokens').get();
const tokens = [];
allTokens.forEach((tokenDoc) => {
tokens.push(tokenDoc.id);
});
if (tokens.length > 0) {
// Send notifications to all tokens.
return await admin.messaging().sendToDevice(tokens, payload);
} else {
return null;
}
});