Vue로 PWA 개발 - 그랜파 개발자
Vue 프로젝트 Beta Test : mylog, 일상의 기록
개발이 진행됨에 따라 소스 코드를 계속 추가해 갑니다.
mylog FCM 보내기
Firebase용 Cloud Functions라고도 알려진 Firebase Functions는 개발자가 서버를 관리하지 않고도 백엔드 코드를 작성하고 배포할 수 있도록 해주는 Firebase에서 제공하는 서버리스 백엔드 서비스입니다.
사용자가 알림을 요청하였다면 firestore에 토큰이 저장되어 있습니다. 한사람의 사용자가 PC와 모바일 등을 사용할 수 있으므로 각 사용자는 여러 토큰이 있습니다. 이 사용자가 마이로그 저자에 대해 구독을 요청하였다면 마이로그 저자가 새 마이로그를 저장하면 푸시 알림이 전송됩니다.
Firebase Cloud Functions v2를 사용하여 FCM(Firebase Cloud Messaging) 알림을 보내려면 Firestore 쓰기 또는 HTTP 요청과 같은 특정 이벤트를 기반으로 트리거될 수 있는 함수를 만듭니다. 이 함수는 Firebase Admin SDK를 사용하여 FCM 알림을 보냅니다.
Firebase Cloud Functions v2를 사용하여 FCM(Firebase Cloud Messaging) 알림을 보내려면 다음과 같은 단계를 따릅니다.
1. Firebase Cloud Functions를 설정
firebase init functions

2. Firebase admin SDK 설치
- 'functions' 디렉터리로 이동합니다.
cd functions
- 'functions' 디렉터리 내에 Firebase Admin SDK를 설치합니다.
npm install firebase-admin
3. FCM을 전송하는 Cloud 함수 만들기
- mylogs 컬렉션에 새로운 마이로그가 저장되면 onDocumentCreated 이벤트가 발생합니다.
- 이 이벤트 데이터에는 마이로그의 각 내용이 있습니다.
const data = snapshot.data();
const authorId = data.userId;
const title = data.title;
const content = data.content;
- subscriptions 컬렉션에서 마이로그 저자의 독자를 찾습니다.
const readersSnapshot = await db.collection('subscriptions')
.where('authorId', '==', authorId)
.get();
- FCM 토큰이 저장된 독자들에게 푸시 메시지를 보냅니다.
admin.messaging().sendEachForMulticast()
functions/index.js
// funcstions/index.js
const { onDocumentCreated } = require('firebase-functions/v2/firestore');
const logger = require("firebase-functions/logger");
const admin = require('firebase-admin');
// Initialize Firebase Admin
admin.initializeApp();
// Reference to Firestore
const db = admin.firestore();
// 마이로그를 쓰면 구독자에게 알림을 전송한다.
exports.sendNewMylogNotification = onDocumentCreated('/mylogs/{mylogId}', async (event) => {
const snapshot = event.data;
if (!snapshot) {
console.log("No data associated with the event");
return;
}
const data = snapshot.data();
// access a particular field as you would any JS property
const authorId = data.userId;
const title = data.title;
const content = data.content;
try {
// userId는 글쓴이 이다. 글쓴이의 독자들을 가져와야 한다.
// subscriptions 컬렉션의 구조: userId: userId, authorId: authorId, createdAt: new Date(),
const readersSnapshot = await db.collection('subscriptions')
.where('authorId', '==', authorId) // Query for posts where 'authorId' matches
.get();
const readerIds = [];
readersSnapshot.forEach((doc) => {
readerIds.push(doc.data().userId);
});
// readerIds 에 userId가 있는 모든 독자에게 알림 전송
for (const userId of readerIds) {
// 각 회원의 토큰을 가져온다.
const tokenSnapshot = await admin.firestore().collection('fcmTokens').doc(userId).get();
// 토근이 있으면 알림을 전송한다.
if (tokenSnapshot.exists) {
// 한 회원이 여러 토큰을 가진다. PC, 모바일 등
const tokens = tokenSnapshot.data().tokens;
// Token을 배열에 넣는다.
const fcmTokens = [];
tokens.forEach((token) => {
// doc.data() is never undefined for query doc snapshots
fcmTokens.push(token.token);
});
try {
const response = await admin.messaging().sendEachForMulticast({
tokens: fcmTokens,
notification: { title: title, body: content }
});
// Check the results of the notifications
response.responses.forEach((response, idx) => {
if (response.success) {
console.log(`Message sent successfully to token: ${fcmTokens[idx]}`);
} else {
console.error(`Failed to send message to token: ${fcmTokens[idx]}`, response.error);
}
});
} catch (error) {
console.error('Error sending multicast notifications:', error);
}
}
}
} catch (error) {
console.error('Error getting readers:', error);
}
});
4. Firebase에 functions를 배포하기
firebase deploy --only functions
5. 실행 결과
마이로그를 저장하면 푸시 알람이 옵니다.

'Vue PWA mylog' 카테고리의 다른 글
mylog 카테고리 (0) | 2024.12.02 |
---|---|
mylog FCM 받기 (1) | 2024.12.01 |
mylog 알림 요청 (1) | 2024.11.28 |
mylog 서비스 워커 등록 (1) | 2024.11.27 |
mylog backend (0) | 2024.11.25 |