Expo의 Server SDK와 Firebase Cloud Functions의 onCreate 메서드를 사용하여,
바라보는 Collection 또는 Document에 문서가 생성되면 특정 집단에 Notifications를 보내는 방법입니다.
onCreate외에도 onUpdate, onDelete, onWrite가 있습니다.
상황에 맞게 사용하면 되나, DB를 계속 바라보는 작업은 리소스가 크기에 신중히 결정할 필요가 있습니다.
const functions = require("firebase-functions");
const admin = require('firebase-admin')
const regionalFunctions = functions.region('asia-northeast3');
const { Expo } = require("expo-server-sdk");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
})
const db = admin.firestore();
exports.noticeUserNotification = regionalFunctions.firestore
.document('Notice/{noticeId}')
.onCreate(async (snap, context) => {
let expo = new Expo();
const notice = snap.data();
let messages = [];
let tickets = [];
const users = await admin.firestore().collection('User').get();
users.forEach((doc) => {
const token = doc.data().pushToken;
if(token) {
messages.push({
to: token,
sound: 'default',
priority: 'high',
title: `공지사항이 등록되었습니다.`,
body: `[${notice.title}]를 확인해주세요`,
channelId:'default'
})
}
})
let chunks = expo.chunkPushNotifications(messages);
for(let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
tickets.push(...ticketChunk);
} catch (error) {
return null;
}
}
})
더 많은 Expo Notifications의 API는 아래에서 확인 가능합니다.
https://docs.expo.dev/versions/latest/sdk/notifications/
Notifications의 이해를 도와주는 문서입니다.
https://docs.expo.dev/push-notifications/sending-notifications/