feat(favorites): migrate to backend API

This commit is contained in:
zetaloop
2026-03-01 22:36:50 +08:00
parent eba8fc7e65
commit 505d9c0168
3 changed files with 120 additions and 111 deletions
+49 -14
View File
@@ -1,20 +1,55 @@
import { useFavoriteStore } from "@/store/favorites"
import type { Favorite } from "@/lib/types"
export function listFavorites() {
return useFavoriteStore.getState().favorites
import { httpJson } from "./http"
type Paginated<T> = {
items: T[]
meta: {
total: number
offset: number
limit: number
}
}
export function listFavoritesByUser(userId: string) {
return useFavoriteStore.getState().favorites.filter((favorite) => favorite.userId === userId)
export async function listFavorites(): Promise<Favorite[]> {
const res = await httpJson<Paginated<Favorite> | Favorite[]>("/api/v1/favorites", {
cache: "no-store",
})
return Array.isArray(res) ? res : res.items
}
export function isFavorited(userId: string, targetType: "player" | "shop", targetId: string) {
return useFavoriteStore
.getState()
.favorites.some(
(favorite) =>
favorite.userId === userId &&
favorite.targetType === targetType &&
favorite.targetId === targetId,
)
export async function isFavorited(
userId: string,
targetType: "player" | "shop",
targetId: string,
): Promise<boolean> {
const searchParams = new URLSearchParams({
targetType,
targetId,
})
const res = await httpJson<{ favorited: boolean }>(
`/api/v1/users/${encodeURIComponent(userId)}/favorites/check?${searchParams.toString()}`,
{
cache: "no-store",
},
)
return res.favorited
}
export async function addFavorite(input: {
targetType: "player" | "shop"
targetId: string
}): Promise<Favorite> {
return await httpJson<Favorite>("/api/v1/favorites", {
method: "POST",
json: input,
cache: "no-store",
})
}
export async function removeFavorite(favoriteId: string): Promise<void> {
await httpJson<unknown>(`/api/v1/favorites/${encodeURIComponent(favoriteId)}`, {
method: "DELETE",
cache: "no-store",
})
}