Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat#7 jisoo/alarm #17

Open
wants to merge 97 commits into
base: main
Choose a base branch
from
Open

Feat#7 jisoo/alarm #17

wants to merge 97 commits into from

Conversation

seojisoosoo
Copy link
Contributor

@seojisoosoo seojisoosoo commented Jul 7, 2023

🔥 Related Issues

💙 작업 내용

지수 배포링크

  • 알림 구현
  • 배포하려고 푸시함

✅ PR Point

알림의 기본 구조

(1) FCM 연결
(2) FCM으로부터 유저의 deviceToken 받아오기
(3) deviceToken을 서버에게 post하기
(4) 서버가 FCM에 알림내용을 push해주기
(5) FCM이 서버에게 받은 알림내용을 클라에게 push해주기

(1) FCM 연결

  • 키 연결해주기
const firebaseConfig = {
  apiKey: import.meta.env.VITE_APP_API_KEY,
  authDomain: import.meta.env.VITE_APP_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_APP_PROJECT_ID,
  storageBucket: import.meta.env.VITE_APP_STORAGE_BUCKET,
  messagingSenderId: import.meta.env.VITE_APP_MESSAGING_SENDER_ID,
  appId: import.meta.env.VITE_APP_APP_ID,
  measurementId: import.meta.env.VITE_APP_MEASUREMENT_ID,
};

const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
  • 알림 권한 허용
  const permission = await Notification.requestPermission();
  if (permission === "denied") {
    console.log("알림 권한 허용 안됨");
    return;
  }
  • 서비스 워커 연결
 navigator.serviceWorker
    .register("firebase-messaging-sw.js")
    .then(function (registration) {
      console.log("Service Worker 등록 성공:", registration);
    })
    .catch(function (error) {
      console.log("Service Worker 등록 실패:", error);
    });

(2) FCM으로부터 유저의 deviceToken 받아오기

  • getToken, messaging 메소드로 받아오기
  const token = await getToken(messaging, {
    vapidKey: import.meta.env.VITE_APP_VAPID_KEY,
  });

(3) deviceToken을 서버에게 post하기

  • (2)에서 받은 토큰 post하기
import axios from "axios";

export async function postToken(token: string) {
  console.log(token);
  const data = await axios.post("/api", { deviceToken: token });

  console.log(data);
  return data;
}

  const { mutate } = useMutation(postToken, {
    onSuccess: (res) => {
      console.log(res);
    },
    onError: (err) => {
      console.log(err);
    },
  });
  • 여기서 포트 번호가 달라서 오류 발생! -> proxy 처리해줌
//vite.config.ts
  server: {
    proxy: {
      "/api": {
        target: "http://43.201.69.115:8080/notifications/",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
        secure: false,
        ws: true,
      },
    },
  },

(4) 서버가 FCM에 알림내용을 push해주기

  • 이건 서버가 알아서 해줌~

(5) FCM이 서버에게 받은 알림내용을 클라에게 push해주기

self.addEventListener("push", function (e) {
  // console.log("push: ", e.data.json());
  if (!e.data.json()) return;

  const resultData = e.data.json().notification;
  const notificationTitle = resultData.title;

  const notificationOptions = {
    body: resultData.body,
    icon: "/tutice.png",
    // tag: resultData.tag,
    // ...resultData,
  };
  console.log(resultData.title, { body: resultData.body, icon: "/tutice.png" });

  // self.registration.showNotification(notificationTitle, notificationOptions);
  e.waitUntil(
    console.log("아니 들어는오냐?"),
    self.registration.showNotification(notificationTitle, notificationOptions),
    console.log("되냐고"),
  );
});

😡 Trouble Shooting

어......아주 많았다.

👀 스크린샷 / GIF / 링크

스크린샷 2023-07-08 오전 12 50 09

📚 Reference

알림보내기
[PWA] Push Notification 상황별 다른 알림 옵션 설정하기

챗 지피티 짱~
스크린샷 2023-07-08 오전 12 51 52

@seojisoosoo seojisoosoo self-assigned this Jul 7, 2023
@seojisoosoo seojisoosoo added feat-function 기능구현했어요 feat-UI UI 만들었어요 지수 지수 담당 labels Jul 7, 2023
@seojisoosoo seojisoosoo marked this pull request as ready for review July 7, 2023 18:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feat-function 기능구현했어요 feat-UI UI 만들었어요 지수 지수 담당
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[ Jisoo ] - 알림 구현
1 participant