Vue로 PWA 개발 - 그랜파 개발자
구독자가 알림을 요청하였다면 firestore에 토큰이 저장되어 있습니다. 한사람의 구독자가 PC와 모바일 등을 사용할 수 있으므로 각 구독자는 여러 토큰이 있습니다. 구독자 또한 여러 사람입니다. 나의 여러 구독자에 대해 각 구독자의 저장된 토큰의 목록을 구하여 이들 토큰에 대해 알림을 전송할 수 있습니다.
푸시 알림은 여러 상황에서 보낼 수 있습니다. 마이로그 앱의 경우 마이로그를 작성하여 firestore에 저장할 때 모든 구독자에게 알림을 보내려고 합니다. 또, 푸시 알림은 마이로그를 저장할 때 구독자에게 보내는 것 뿐 아니라 여러 필요에 따라 전송할 수도 있습니다. 그러므로 우선 한사람의 회원에 대해 알림을 전송하는 기능을 먼저 구현해 봅시다.
To send Firebase Cloud Messaging (FCM) notifications using Firebase Cloud Functions v2, you'll create a function that can be triggered based on specific events, such as Firestore writes, or HTTP requests. This function will use the Firebase Admin SDK to send FCM notifications.
Firebase Cloud Functions v2를 사용하여 FCM(Firebase Cloud Messaging) 알림을 보내려면 Firestore 쓰기 또는 HTTP 요청과 같은 특정 이벤트를 기반으로 트리거될 수 있는 함수를 만듭니다. 이 함수는 Firebase Admin SDK를 사용하여 FCM 알림을 보냅니다.
Here's how you can create a Firebase Cloud Function (v2) to send FCM notifications:
FCM 알림을 보내기 위해 Firebase Cloud Function(v2)을 만드는 방법은 다음과 같습니다.
Set up Firebase Admin SDK: Ensure you have the Firebase Admin SDK set up in your Firebase Cloud Functions environment to send notifications.
Firebase Admin SDK 설정: 알림을 보내려면 Firebase Cloud Functions 환경에 Firebase Admin SDK가 설정되어 있는지 확인하세요.
Create a Cloud Function: The function can be triggered by Firestore events (e.g., when a new document is created) or via an HTTP request.
Cloud 함수 만들기: 이 함수는 Firestore 이벤트(예: 새 문서가 생성될 때) 또는 HTTP 요청을 통해 트리거될 수 있습니다
Send FCM notifications using the Firebase Admin SDK.
Firebase Admin SDK를 사용하여 FCM 알림을 보냅니다.
To use Firebase Admin SDK in your Cloud Functions, you need to install the Admin SDK in your functions folder:
Cloud Functions에서 Firebase Admin SDK를 사용하려면 함수 폴더에 Admin SDK를 설치해야 합니다.
npm install firebase-admin
Here is an example of creating a Firebase Cloud Function in v2 that sends FCM notifications when triggered by a Firestore event or an HTTP request.
다음은 Firestore 이벤트 또는 HTTP 요청에 의해 트리거될 때 FCM 알림을 보내는 v2에서 Firebase Cloud 함수를 생성하는 예입니다.
// Import the Firebase Admin SDK
const functions = require('firebase-functions/v2');
const admin = require('firebase-admin');
// Initialize the Firebase Admin SDK
admin.initializeApp();
// Create a function that triggers when a new document is added to the 'posts' collection
exports.sendPostNotification = functions.firestore
.document('posts/{postId}')
.onCreate(async (snapshot, context) => {
const newPost = snapshot.data();
const postId = context.params.postId;
// Create the notification payload
const payload = {
notification: {
title: `New Post: ${newPost.title}`,
body: newPost.content,
click_action: `https://your-app.com/posts/${postId}`, // Link to open when notification is clicked
},
};
try {
// Get the list of FCM tokens from Firestore (or another source)
const tokensSnapshot = await admin.firestore().collection('fcmTokens').get();
const tokens = tokensSnapshot.docs.map(doc => doc.data().token);
if (tokens.length > 0) {
// Send notifications to all FCM tokens
const response = await admin.messaging().sendToDevice(tokens, payload);
console.log('Successfully sent message:', response);
} else {
console.log('No tokens available for notification');
}
} catch (error) {
console.error('Error sending notification:', error);
}
});
1. Firestore Trigger: Firestore 트리거:
2. Notification Payload: 알림 페이로드:
3. Fetching FCM Tokens: FCM 토큰 가져오기:
4. Sending Notifications: 알림 보내기:
Alternatively, if you want to trigger the FCM notifications via an HTTP request (e.g., from your frontend or another system), you can create a function with an HTTP trigger:
또는 HTTP 요청(예: 프런트엔드 또는 다른 시스템)을 통해 FCM 알림을 트리거하려는 경우 HTTP 트리거를 사용하여 함수를 생성할 수 있습니다.
exports.sendCustomNotification = functions.https.onRequest(async (req, res) => {
const { title, body, token } = req.body;
const payload = {
notification: {
title: title,
body: body,
},
};
try {
// Send notification to the given FCM token
const response = await admin.messaging().sendToDevice(token, payload);
res.status(200).send(`Notification sent successfully: ${response}`);
} catch (error) {
console.error('Error sending notification:', error);
res.status(500).send(`Error sending notification: ${error}`);
}
});
1. HTTP Trigger: HTTP 트리거:
2. Notification Payload: 알림 페이로드:
3. Sending the Notification: 알림 보내기:
Deploy the function using the Firebase CLI:
Firebase CLI를 사용하여 함수를 배포합니다.
firebase deploy --only functions
This is a simple way to implement FCM using Firebase Cloud Functions v2..
이는 Firebase Cloud Functions v2를 사용하여 FCM을 구현하는 간단한 방법입니다.