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
173 changes: 173 additions & 0 deletions src/apis/notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import { apiClient } from "@/apis/client";
import type { CommonResponse } from "@/types/api";

// 알림 유형
export type NotificationType = "MISSION_RECOMMENDATION";

// 딥링크 대상 유형
export type NotificationReferenceType = "MISSION";

// 기기 유형
export type DeviceType = "ANDROID" | "IOS" | "WEB";

// 알림 항목
export interface NotificationItem {
id: number;
type: NotificationType;
title: string;
body: string;
referenceType: NotificationReferenceType | null;
referenceId: number | null;
read: boolean;
createdAt: string;
}

// 알림 목록 조회 응답
export interface Notifications {
notifications: NotificationItem[];
nextCursor: number | null;
hasNext: boolean;
}

// 알림 목록 조회 파라미터
export interface NotificationsParams {
cursor?: number;
size?: number;
}

// 미읽음 알림 개수 조회 응답
export interface UnreadNotificationCount {
unreadCount: number;
}

// 알림 설정 조회·변경 응답
export interface NotificationSettings {
pushEnabled: boolean;
}

// 알림 설정 변경 요청
export interface UpdateNotificationSettingsParams {
pushEnabled: boolean;
}

// FCM 토큰 등록 요청
export type RegisterFcmTokenParams = {
token: string;
deviceType: DeviceType;
} & (
| {
latitude: number;
longitude: number;
}
| {
latitude?: never;
longitude?: never;
}
);

// FCM 토큰 등록 응답
export interface RegisteredFcmToken {
id: number;
deviceType: DeviceType;
}

// 인앱 알림 목록 조회
// GET /api/notifications
export const getNotifications = async (
params: NotificationsParams = {},
): Promise<Notifications> => {
const response = await apiClient.get<CommonResponse<Notifications>>(
"/api/notifications",
{
params: {
...params,
size: params.size ?? 20,
},
},
);

return response.data.result;
};

// 미읽음 알림 개수 조회
// GET /api/notifications/unread-count
export const getUnreadNotificationCount =
async (): Promise<UnreadNotificationCount> => {
const response = await apiClient.get<
CommonResponse<UnreadNotificationCount>
>("/api/notifications/unread-count");

return response.data.result;
};

// 알림 설정 조회
// GET /api/users/me/notification-settings
export const getNotificationSettings =
async (): Promise<NotificationSettings> => {
const response = await apiClient.get<CommonResponse<NotificationSettings>>(
"/api/users/me/notification-settings",
);

return response.data.result;
};

// 알림 설정 변경
// PATCH /api/users/me/notification-settings
export const updateNotificationSettings = async (
params: UpdateNotificationSettingsParams,
): Promise<NotificationSettings> => {
const response = await apiClient.patch<CommonResponse<NotificationSettings>>(
"/api/users/me/notification-settings",
params,
);

return response.data.result;
};

// 알림 읽음 처리
// PATCH /api/notifications/{notificationId}/read
export const markNotificationAsRead = async (
notificationId: number,
): Promise<string> => {
const response = await apiClient.patch<CommonResponse<string>>(
`/api/notifications/${notificationId}/read`,
);

return response.data.result;
};

// 알림 전체 읽음 처리
// PATCH /api/notifications/read-all
export const markAllNotificationsAsRead = async (): Promise<string> => {
const response = await apiClient.patch<CommonResponse<string>>(
"/api/notifications/read-all",
);

return response.data.result;
};

// FCM 토큰 등록
// POST /api/notifications/fcm-tokens
export const registerFcmToken = async (
params: RegisterFcmTokenParams,
): Promise<RegisteredFcmToken> => {
const response = await apiClient.post<CommonResponse<RegisteredFcmToken>>(
"/api/notifications/fcm-tokens",
params,
);

return response.data.result;
};

// FCM 토큰 해제
// DELETE /api/notifications/fcm-tokens
export const deleteFcmToken = async (token: string): Promise<string> => {
const response = await apiClient.delete<CommonResponse<string>>(
"/api/notifications/fcm-tokens",
{
params: { token },
},
);

return response.data.result;
};
13 changes: 9 additions & 4 deletions src/components/common/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ import questyProfile from "@/assets/questy.svg";
import { useNavigate } from "react-router-dom";
import { PATH } from "@/routes/paths";
import { ReactNode } from "react";
import { useUnreadNotificationCount } from "@/hooks/queries/useNotification";

interface HeaderProps {
children?: ReactNode;
}
export function Header({ children }: HeaderProps) {
const navigate = useNavigate();
const { data: unreadData } = useUnreadNotificationCount();
const unreadCount = unreadData?.unreadCount ?? 0;
return (
<header className="sticky top-0 z-20 flex min-h-[66px] shrink-0 items-center justify-between border-b border-[#dcecf8] bg-white/95 px-[22px] backdrop-blur-xl">
<button
Expand All @@ -25,13 +28,15 @@ export function Header({ children }: HeaderProps) {
<button
className="relative grid h-10 w-10 place-items-center bg-transparent text-[#8290a2] transition active:scale-95"
type="button"
aria-label="알림 3개"
aria-label={`알림 ${unreadCount}개`}
onClick={() => navigate(PATH.NOTIFICATION)}
>
<Bell size={19} strokeWidth={2.2} />
<span className="absolute right-[1px] top-[1px] grid h-[16px] min-w-[16px] place-items-center rounded-full border-2 border-white bg-[#f26464] px-0.5 text-[8px] font-black leading-none text-white">
3
</span>
{unreadCount > 0 && (
<span className="absolute right-[1px] top-[1px] grid h-[16px] min-w-[16px] place-items-center rounded-full border-2 border-white bg-[#f26464] px-0.5 text-[8px] font-black leading-none text-white">
{unreadCount > 99 ? "99+" : unreadCount}
</span>
)}
</button>
</div>
</header>
Expand Down
4 changes: 3 additions & 1 deletion src/components/common/NotificationCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ interface NotificationCardProps {
amount?: number | null;
createdAt: string;
read?: boolean;
onRead?: (id: number, read: boolean) => void;
}

export function NotificationCard({
Expand All @@ -42,13 +43,14 @@ export function NotificationCard({
amount,
createdAt,
read = false,
onRead,
}: NotificationCardProps) {
const unread = !read;
const { icon, iconBg } = notificationStyles[type];
return (
<ContentCard
key={id}
// onClick={() => handleRead(notification.id)}
onClick={() => onRead?.(id, read)}
className={`relative cursor-pointer transition ${unread ? "bg-white" : "!bg-[#F8FAFC]"}`}
>
<div className="flex gap-3">
Expand Down
73 changes: 73 additions & 0 deletions src/hooks/mutation/useNotification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import {
deleteFcmToken,
markAllNotificationsAsRead,
markNotificationAsRead,
registerFcmToken,
updateNotificationSettings,
} from "@/apis/notification";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { notificationKeys } from "../queries/useNotification";

// 알림 설정 변경
export const useUpdateNotificationSettings = () => {
const queryClient = useQueryClient();

return useMutation({
mutationFn: updateNotificationSettings,
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: notificationKeys.settings,
});
},
});
};

// 알림 하나 읽음 처리
export const useMarkNotificationAsRead = () => {
const queryClient = useQueryClient();

return useMutation({
mutationFn: markNotificationAsRead,
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({
queryKey: notificationKeys.lists,
}),
queryClient.invalidateQueries({
queryKey: notificationKeys.unreadCount,
}),
]);
},
});
};

// 알림 전체 읽음 처리
export const useMarkAllNotificationsAsRead = () => {
const queryClient = useQueryClient();

return useMutation({
mutationFn: markAllNotificationsAsRead,
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({
queryKey: notificationKeys.lists,
}),
queryClient.invalidateQueries({
queryKey: notificationKeys.unreadCount,
}),
]);
},
});
};

// FCM 토큰 등록
export const useRegisterFcmToken = () =>
useMutation({
mutationFn: registerFcmToken,
});

// FCM 토큰 해제
export const useDeleteFcmToken = () =>
useMutation({
mutationFn: deleteFcmToken,
});
47 changes: 47 additions & 0 deletions src/hooks/queries/useNotification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";

import {
getNotifications,
getUnreadNotificationCount,
getNotificationSettings,
} from "@/apis/notification";

// 쿼리 키
export const notificationKeys = {
all: ["notifications"] as const,
lists: ["notifications", "list"] as const,
list: (size: number) => ["notifications", "list", size] as const,
unreadCount: ["notifications", "unread-count"] as const,
settings: ["notifications", "settings"] as const,
};

// 알림 목록 조회: 커서 기반 더보기
export const useNotifications = (size = 20) =>
useInfiniteQuery({
queryKey: notificationKeys.list(size),
queryFn: ({ pageParam }) =>
getNotifications({
cursor: pageParam,
size,
}),
initialPageParam: undefined as number | undefined,
getNextPageParam: (lastPage) =>
lastPage.hasNext ? (lastPage.nextCursor ?? undefined) : undefined,
staleTime: 30 * 1000,
});

// 미읽음 알림 개수 조회
export const useUnreadNotificationCount = () =>
useQuery({
queryKey: notificationKeys.unreadCount,
queryFn: getUnreadNotificationCount,
staleTime: 30 * 1000,
});

// 알림 설정 조회
export const useNotificationSettings = () =>
useQuery({
queryKey: notificationKeys.settings,
queryFn: getNotificationSettings,
staleTime: 5 * 60 * 1000,
});
Loading
Loading