Refactor: FCM 토큰을 불러와서 서버에 바로 저장하도록 로직 개선

This commit is contained in:
홍창기 2024-09-27 15:46:35 +09:00
parent 765aa52912
commit 91c9faa669
7 changed files with 30 additions and 68 deletions

View File

@ -1,5 +1,6 @@
import api from '@/api/axiosConfig';
import { MemberResponse, RefreshTokenResponse } from '@/types';
import { getFcmToken } from './firebaseConfig';
export async function reissueToken() {
return api.post<RefreshTokenResponse>('/auth/reissue', null, { withCredentials: true }).then(({ data }) => data);
@ -13,8 +14,9 @@ export async function logout() {
return api.post('/auth/logout').then(({ data }) => data);
}
export async function saveFcmToken(token: string) {
return api.post('/auth/fcm', { token }).then(({ data }) => data);
export async function saveFcmToken() {
const fcmToken = await getFcmToken();
return api.post('/auth/fcm', { token: fcmToken }).then(({ data }) => ({ data, fcmToken }));
}
export async function createFcmNotification() {

View File

@ -1,5 +1,5 @@
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from 'firebase/messaging';
import { getMessaging, onMessage } from 'firebase/messaging';
const firebaseConfig = {
apiKey: String(import.meta.env.VITE_FIREBASE_API_KEY),
@ -22,30 +22,31 @@ const getFcmToken = async () => {
return existingToken;
}
try {
const permission = await Notification.requestPermission();
// try {
// const permission = await Notification.requestPermission();
if (permission === 'granted') {
console.log('알림 권한이 허용되었습니다.');
// if (permission === 'granted') {
// console.log('알림 권한이 허용되었습니다.');
console.log('FCM 토큰 발급 중...');
const currentToken = await getToken(messaging, {
vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
});
console.log('FCM 토큰 발급 성공');
// console.log('FCM 토큰 발급 중...');
// const currentToken = await getToken(messaging, {
// vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_x38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
// });
// console.log('FCM 토큰 발급 성공');
if (currentToken) {
sessionStorage.setItem('fcmToken', currentToken);
return currentToken;
}
// if (currentToken) {
// sessionStorage.setItem('fcmToken', currentToken);
// return currentToken;
// }
console.warn('FCM 토큰을 가져올 수 없습니다.');
} else {
console.log('알림 권한이 거부되었습니다.');
}
} catch (error) {
console.error('FCM 토큰을 가져오는 중 오류가 발생했습니다. : ', error);
}
// console.warn('FCM 토큰을 가져올 수 없습니다.');
// } else {
// console.log('알림 권한이 거부되었습니다.');
// }
// } catch (error) {
// console.error('FCM 토큰을 가져오는 중 오류가 발생했습니다. : ', error);
// }
return null;
};
const handleForegroundMessages = () => {

View File

@ -1,14 +1,11 @@
import useAuthStore from '@/stores/useAuthStore';
import useProfileQuery from '@/queries/auth/useProfileQuery';
import useGetFcmTokenQuery from '@/queries/auth/useGetFcmTokenQuery';
import useSaveFcmTokenQuery from '@/queries/auth/useSaveFcmTokenQuery';
export default function useHandleOAuthCallback() {
const queryParams = new URLSearchParams(window.location.search);
const accessToken = queryParams.get('accessToken');
const setToken = useAuthStore((state) => state.setToken);
const setProfile = useAuthStore((state) => state.setProfile);
const setFcmToken = useAuthStore((state) => state.setFcmToken);
if (accessToken) {
setToken(accessToken);
@ -19,8 +16,4 @@ export default function useHandleOAuthCallback() {
if (profile) {
setProfile(profile);
}
const { data: fcmToken } = useGetFcmTokenQuery(); // FCM 토큰을 가져온다.
setFcmToken(fcmToken ?? ''); // FCM 토큰을 authStore에 저장한다.
useSaveFcmTokenQuery().mutate(fcmToken ?? ''); // FCM 토큰을 서버에 전송한다.
}

View File

@ -1,36 +1,23 @@
import { createFcmNotification, saveFcmToken } from '@/api/authApi';
import { getFcmToken, handleForegroundMessages } from '@/api/firebaseConfig';
import { handleForegroundMessages } from '@/api/firebaseConfig';
import { Button } from '@/components/ui/button';
export default function FirebaseTest() {
const handleSaveFcmToken = async () => {
const fcmToken = await getFcmToken();
if (fcmToken) {
await saveFcmToken(fcmToken);
return;
}
console.log('FCM 토큰이 없습니다.');
await saveFcmToken();
};
const handleCreateNotification = async () => {
await createFcmNotification();
};
handleSaveFcmToken();
handleForegroundMessages();
return (
<div>
<h1 className="heading p-2">hello, firebase!</h1>
<div className="p-2">
<Button
onClick={handleSaveFcmToken}
variant="outlinePrimary"
className="mr-2"
>
FCM
</Button>
<Button
onClick={handleCreateNotification}
variant="outlinePrimary"

View File

@ -1,9 +0,0 @@
import { getFcmToken } from '@/api/firebaseConfig';
import { useSuspenseQuery } from '@tanstack/react-query';
export default function useGetFcmTokenQuery() {
return useSuspenseQuery({
queryKey: ['fcmToken'],
queryFn: getFcmToken,
});
}

View File

@ -1,8 +0,0 @@
import { saveFcmToken } from '@/api/authApi';
import { useMutation } from '@tanstack/react-query';
export default function useSaveFcmTokenQuery() {
return useMutation({
mutationFn: (fcmToken: string) => saveFcmToken(fcmToken),
});
}

View File

@ -5,10 +5,8 @@ import { MemberResponse } from '@/types';
interface AuthState {
accessToken: string;
profile: MemberResponse | null;
fcmToken: string;
setToken: (token: string) => void;
setProfile: (profile: MemberResponse) => void;
setFcmToken: (fcmToken: string) => void;
clearAuth: () => void;
}
@ -17,11 +15,9 @@ const useAuthStore = create<AuthState>()(
(set) => ({
accessToken: '',
profile: null,
fcmToken: '',
setToken: (token: string) => set({ accessToken: token }),
setProfile: (profile: MemberResponse) => set({ profile }),
setFcmToken: (fcmToken: string) => set({ fcmToken }),
clearAuth: () => set({ accessToken: '', profile: null, fcmToken: '' }),
clearAuth: () => set({ accessToken: '', profile: null }),
}),
{
name: 'auth-storage',