Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions public/sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Service Worker
self.addEventListener('push', event => {
const data = event.data?.json();

event.waitUntil(
self.registration.showNotification(data?.title ?? '알림', {
body: data?.body ?? '',
icon: '/icon.png',
})
);
});
28 changes: 28 additions & 0 deletions src/apis/apiHooks/usePushNotification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { getVapidPublicKey, postPushSubscription } from "@/apis/notification/notification";

export const usePushNotification = () => {
const subscribePushNotification = async () => {
try {
const vapidPublicKeyResponse = await getVapidPublicKey();
const vapidPublicKey = vapidPublicKeyResponse.data.publicKey;

const registration = await navigator.serviceWorker.ready; // 서비스 워커 가져오기(대기)
const subscription = await registration.pushManager.subscribe({ // 푸시 구독 요청
userVisibleOnly: true,
applicationServerKey: vapidPublicKey,
});

await postPushSubscription({
endpoint: subscription.endpoint,
keys: {
p256dh: btoa(String.fromCharCode(...new Uint8Array(subscription.getKey('p256dh')!))),
auth: btoa(String.fromCharCode(...new Uint8Array(subscription.getKey('auth')!))),
}
});
} catch (error) {
console.error('푸시 구독 실패: ', error);
}
};

return {subscribePushNotification};
};
15 changes: 15 additions & 0 deletions src/apis/notification/notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { instance } from '@/apis/instance';
import type { ApiEnvelope } from '@/types/api.type';
import type { GetVapidPublicKeyResponse, PostPushSubscriptionRequest } from '@/types/notification/notification.type';

// 알림 구독 키 조회
export const getVapidPublicKey = async (): Promise<ApiEnvelope<GetVapidPublicKeyResponse>> => {
const response = await instance.get('/notifications/web-push/public-key');
return response.data;
};

// 알림 구독
export const postPushSubscription = async (body: PostPushSubscriptionRequest): Promise<ApiEnvelope<null>> => {
const response = await instance.post('/notifications/web-push/subscriptions', body);
return response.data;
};
6 changes: 6 additions & 0 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import App from './App';

const queryClient = new QueryClient();

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(() => console.log('Service Worker 등록 성공'))
.catch(error => console.error('Service Worker 등록 실패: ', error));
}

createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
Expand Down
3 changes: 3 additions & 0 deletions src/pages/login/components/OAuthCallback.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuthStore } from '@/stores/authStore';
import { usePushNotification } from '@/apis/apiHooks/usePushNotification';

const OAuthCallback = () => {
const [searchParams] = useSearchParams();
const { login } = useAuthStore();
const navigate = useNavigate();
const { subscribePushNotification } = usePushNotification();

useEffect(() => {
const accessToken = searchParams.get('accessToken');
Expand All @@ -17,6 +19,7 @@ const OAuthCallback = () => {
}

login(accessToken);
subscribePushNotification();

// 초대 링크로 왔었으면
const inviteCode = sessionStorage.getItem('inviteCode');
Expand Down
13 changes: 13 additions & 0 deletions src/types/notification/notification.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// 알림 구독 키 조회
export interface GetVapidPublicKeyResponse {
publicKey: string;
};

// 알림 구독
export interface PostPushSubscriptionRequest {
endpoint: string;
keys: {
p256dh: string;
auth: string;
};
};
Loading