[Functions/Flutter] Firebase Functions 사용해서 FCM 푸시알람 구현하기 2/3 - Functions 구현

찌니·2023년 7월 25일
1

Fcm+Functions

목록 보기
2/3
post-thumbnail

본인은 관리자가 유저들에게 푸시 알림 보내는 것을 목적으로 하며 firestore에 저장된 모든 유저, 특정 유저 두 경우의 로직을 구현했습니다. functions는 javascript로 구현! 매우 힘들어따..😂

firebase functions에 사용 등록을 하면 가이드가 나온다 요로코롬 따라해보자

index.js (1차 모바일 관리자 모드 전용)


/* eslint-disable no-unused-vars */
const {onRequest} = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
/* eslint-enable no-unused-vars */

const admin = require('firebase-admin');
const functions = require('firebase-functions');

admin.initializeApp(functions.config().firebase);

const db = admin.firestore();

// 모든 유저에게 공지사항 업데이트 공지
exports.update = functions.https.onCall((data, context) => {
  var tokens=[];

  const payload = {
    notification: {
      title: '공지사항 업데이트',
      body: `공지사항이 업데이트 되었습니다.`,
    },
  };
    // FireStore 에서 데이터 읽어오기
  db.collection('user').get().then((snapshot) => {
    snapshot.forEach((doc) => {
      if (doc.data().fcmToken!=null && doc.data().fcmToken!='' &&
        doc.data().fcmToken!=undefined) {
        tokens.push(doc.data().fcmToken);
      }
    });

    console.log(tokens);

    if (tokens.length > 0) {
      admin.messaging().sendToDevice(tokens, payload)
          .then((response) => {
            console.log('Successfully sent message:', response);
            return true;
          });
    }
    if (tokens.length==0) {
      console.log('Error getting documents');
    }
  })
      .catch((err) => {
        console.log('Error getting documents', err);
        tokens.push('Error getting documents');
        return tokens;
      });
});

// qna에 질문을 올린 유저에게 알림 전송
exports.updateAnswer = functions.https.onCall((data, context) => {
  const payload = {
    notification: {
      title: '답변 업데이트',
      body: `답변이 업데이트 되었습니다.`,
    },
  };

  if (data.call!=null && data.call!='' &&
  data.call!=undefined) {
    db.collection('user').doc(data.call).get()
        .then((snapshot) => {
          console.log(snapshot.data().fcmToken);
          if (snapshot.data().fcmToken!=null && snapshot.data().fcmToken!='' &&
            snapshot.data().fcmToken!=undefined) {
            var token = snapshot.data().fcmToken;

            admin.messaging().sendToDevice(token, payload)
                .then((response) => {
                  console.log('Successfully sent message:', response);
                  return true;
                });
          }
        })
        .catch((err) => {
          console.log('Error getting documents', err);
          return false;
        });
  }
});

본인 firebase deploy 과정에서 나왔던 오류


/ eslint-disable no-unused-vars /
/ eslint-enable no-unused-vars /
추가!!

.eslintrc.js

"quotes": [0, "double", {"avoidEscape": false}],
"no-var": 0,
윗 문장을 rules에 추가!!

함수 배포를 마치고 앱에서 실행 코드를 만들어준다 사용 라이브러리 : cloud_functions

pushFcmService.dart

Future<void> pushFCM(bool update) async {
    try {
      HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('update');

      final results = await callable();
      print('pushFCM: success');
    } catch (e) {
      print('pushFAQ: $e');
      throw Exception("pushFAQ: $e");
    }
  }

실행을 하면 요로코롬 3명의 유저에게 잘 알림이 간 것을 볼 수 있다!!

profile
찌니's develog

0개의 댓글