|
| 1 | +/** |
| 2 | + * Copyright 2024 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +// Import the Firebase SDK for Google Cloud Functions. |
| 18 | +const functions = require('firebase-functions'); |
| 19 | +// Import and initialize the Firebase Admin SDK. |
| 20 | +const admin = require('firebase-admin'); |
| 21 | +admin.initializeApp(); |
| 22 | + |
| 23 | +// Import the FCM SDK |
| 24 | +const messaging = admin.messaging(); |
| 25 | + |
| 26 | +exports.sendMessage = functions.https.onCall(async (data) => { |
| 27 | + const {sendTo, isToken, notificationTitle, notificationBody, messageFields} = |
| 28 | + data; |
| 29 | + |
| 30 | + const message = { |
| 31 | + notification: { |
| 32 | + title: notificationTitle, |
| 33 | + body: notificationBody, |
| 34 | + }, |
| 35 | + data: messageFields, |
| 36 | + }; |
| 37 | + |
| 38 | + if (isToken) { |
| 39 | + message.token = sendTo; |
| 40 | + } else { |
| 41 | + message.topic = sendTo; |
| 42 | + } |
| 43 | + |
| 44 | + try { |
| 45 | + const response = await messaging.send(message); |
| 46 | + console.log('Successfully sent message:', response); |
| 47 | + return response; // Optionally return the FCM response to the client |
| 48 | + } catch (error) { |
| 49 | + console.error('Error sending message:', error); |
| 50 | + throw new functions.https.HttpsError('internal', error.message); |
| 51 | + } |
| 52 | +}); |
0 commit comments