[Pill So Good] (3) Firebase 메세지 발송

HY·2022년 8월 1일
0

pill-so-good

목록 보기
3/6
post-thumbnail

발단

사용자가 약을 복용할 시간이 되면 알림을 발송하기 위해 node-scheduler와 Firebase를 사용했다.
node-scheduler로 1분 마다 조건에 해당되는 알림 데이터를 조회하고, Firebase를 거쳐 알림을 발송한다.

약 복용 알림 시퀀스

약 복용 알림을 구현하기 위해 사용자 - 앱 - 서버 - DB 간 시퀀스를 정리하였다.

서버 구현

서버가 시작되면 1분마다 약 복용 알림 기능이 실행되도록 구현하였다.

// server.ts 중 firebase 파트
import schedule from 'node-schedule';
import { sendMedicationAlert, initFirebaseAdmin } from "../src/batch/MedicationAlert"

initFirebaseAdmin();
// every minute cron
schedule.scheduleJob('* * * * *', ()=>{ 
  sendMedicationAlert();
});

메세지 발송 기능

// MedicationAlert.ts
const Prescription = require('../models/prescription')
const moment = require("moment")

const admin = require('firebase-admin')
const serviceAccount = require('./beb-04-pillsogood-firebase-adminsdk-t99tv-8d3798f0d2.json');

// firebase admin 초기화
export const initFirebaseAdmin = () => {
    admin.initializeApp({
      // firebase에서 발급받은 인증 정보 확인
        credential: admin.credential.cert(serviceAccount)
    });
}

export const sendMedicationAlert = async () => {
	
  // Prescription 컬렉션에서 잔여 복용량이 0 이상, 알림 시간이 현재 시간으로 설정 된 데이터 조회 
    const alivePrescription = await Prescription.find({
        lastMedicationCount: {$ne:0},
        alertTime:moment().format("HH:mm")
      // userId로 User 컬렉션에 저장된 firebaseToken을 조회한다. 
    }).populate("userId")

    for (let alertData of alivePrescription) {
      // 발송할 알림 데이터 생성
        const message = {
            android: {
                priority:'high',
                notification: {
                    title: `Pill So Good!`,
                    body: `${alertData.medicine} 먹을 시간입니다.`
                }
            },
            token: alertData.userId.firebaseToken
        }
    	// 메세지 발송
        await admin.messaging().send(message);
    }
}

시연

profile
사실은 공부를 비밀스럽게 하고 싶었다

0개의 댓글