feat: 나만의 각 1단계 — 공식 각 두 개를 섞어 내 각 만들기(점수는 낮은 쪽), 로그인 없이 1개·로그인하면 계정 저장, 친구에게 보낸 링크로 내 동네 점수 보기
This commit is contained in:
1 parent
96cbd19c61
commit
a8a126f6a5
18 files changed
+842
-6
No files matched your search
@@ -362,3 +362,13 @@ class CommentLike(Base):
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class MyGak(Base):
|
||||
__tablename__ = "my_gak"
|
||||
|
||||
my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
index_a: Mapped[int] = mapped_column(SmallInteger)
|
||||
index_b: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -0,0 +1,24 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import MyGak
|
||||
|
||||
|
||||
class MyGakCRUD:
|
||||
async def of_user(self, s: AsyncSession, user_id: uuid.UUID) -> list[MyGak]:
|
||||
return list((await s.scalars(select(MyGak).where(MyGak.user_id == user_id).order_by(MyGak.my_gak_id))).all())
|
||||
|
||||
async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int:
|
||||
return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id))
|
||||
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, a: int, b: int) -> MyGak:
|
||||
"""같은 조합이 이미 있으면 그것을 돌려준다."""
|
||||
await s.execute(insert(MyGak).values(user_id=user_id, index_a=a, index_b=b).on_conflict_do_nothing())
|
||||
return await s.scalar(select(MyGak).where(MyGak.user_id == user_id, MyGak.index_a == a, MyGak.index_b == b))
|
||||
|
||||
async def delete(self, s: AsyncSession, user_id: uuid.UUID, my_gak_id: int) -> bool:
|
||||
res = await s.execute(delete(MyGak).where(MyGak.my_gak_id == my_gak_id, MyGak.user_id == user_id).returning(MyGak.my_gak_id))
|
||||
return res.first() is not None
|
||||
@@ -248,6 +248,17 @@ CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||
PRIMARY KEY (comment_id, user_id)
|
||||
);
|
||||
|
||||
-- 나만의 각: 공식 각 두 개를 섞은 조합. 점수는 저장하지 않고 두 각의 오늘 점수 중 낮은 쪽을 그때 쓴다
|
||||
CREATE TABLE IF NOT EXISTS public.my_gak (
|
||||
my_gak_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
index_a SMALLINT NOT NULL, -- 같은 조합은 하나로: 작은 index_id 가 a
|
||||
index_b SMALLINT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CHECK (index_a < index_b)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_my_gak ON public.my_gak (user_id, index_a, index_b);
|
||||
|
||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||
|
||||
-- 구 목록.
|
||||
|
||||
@@ -11,6 +11,7 @@ from router.v1.auth.account import router as auth_router
|
||||
from router.v1.feed.feed import router as feed_router
|
||||
from router.v1.image.image import router as image_router
|
||||
from router.v1.index.index import router as index_router
|
||||
from router.v1.my_gak.my_gak import router as my_gak_router
|
||||
from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
@@ -42,6 +43,7 @@ app.include_router(season_router)
|
||||
app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(my_gak_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
app.include_router(seo_router)
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,41 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import MyGak, User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.my_gak.protocol import MyGakData, Req_MyGak, Res_MyGak, Res_MyGakList
|
||||
from services.my_gak_service import MyGakService
|
||||
|
||||
router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"])
|
||||
|
||||
|
||||
def _data(g: MyGak) -> MyGakData:
|
||||
return MyGakData(my_gak_id=g.my_gak_id, index_ids=[g.index_a, g.index_b])
|
||||
|
||||
|
||||
@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각과 섞을 수 있는 공식 각 (로그인 없이도 섞을 수 있는 목록은 보임)")
|
||||
async def list_my_gak(user: Optional[User] = Depends(optional_user), service: MyGakService = Depends()) -> Res_MyGakList:
|
||||
err, mixable = await service.mixable()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_MyGakList(result=error_info(err))
|
||||
if user is None:
|
||||
return Res_MyGakList(mixable=mixable)
|
||||
err, rows = await service.mine(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_MyGakList(result=error_info(err))
|
||||
return Res_MyGakList(mixable=mixable, items=[_data(g) for g in rows])
|
||||
|
||||
|
||||
@router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="공식 각 두 개를 섞어 내 각 만들기 (같은 조합이면 있는 것을 돌려줌)")
|
||||
async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak:
|
||||
err, g = await service.add(user, req.index_ids)
|
||||
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
|
||||
|
||||
|
||||
@router.delete("/{my_gak_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 각 지우기")
|
||||
async def delete_my_gak(my_gak_id: int = Path(...), user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete(user, my_gak_id)))
|
||||
@@ -0,0 +1,23 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class MyGakData(WebPacketProtocol):
|
||||
my_gak_id: int
|
||||
index_ids: list[int] = Field(description="섞은 공식 각 두 개. 점수는 두 각의 오늘 점수 중 낮은 쪽")
|
||||
|
||||
|
||||
class Req_MyGak(Req_WebPacketProtocol):
|
||||
index_ids: list[int] = Field(min_length=2, max_length=2, description="섞을 공식 각 두 개")
|
||||
|
||||
|
||||
class Res_MyGakList(Res_WebPacketProtocol):
|
||||
mixable: list[int] = Field(default=[], description="섞을 수 있는 공식 각 index_id")
|
||||
items: list[MyGakData] = Field(default=[], description="내 각. 로그인하지 않았으면 비어 있음")
|
||||
|
||||
|
||||
class Res_MyGak(Res_WebPacketProtocol):
|
||||
item: Optional[MyGakData] = None
|
||||
@@ -0,0 +1,48 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import MyGak, User
|
||||
from common.enums import ErrorType, IndexCategory
|
||||
from crud.index_crud import IndexCRUD
|
||||
from crud.my_gak_crud import MyGakCRUD
|
||||
|
||||
# 한 사람이 만들 수 있는 조합 수
|
||||
MAX_PER_USER = 20
|
||||
|
||||
|
||||
class MyGakService:
|
||||
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexCRUD = Depends(IndexCRUD)) -> None:
|
||||
self.crud, self.index = crud, index
|
||||
|
||||
async def mixable(self) -> tuple[ErrorType, list[int]]:
|
||||
"""섞을 수 있는 공식 각. 생활 고민(우산·교통체증처럼 불편한 날을 알리는 각)은 좋은 날 각과 섞으면 뜻이 뒤집혀 뺀다."""
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.definitions(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
return ErrorType.SUCCESS, [d.index_id for d in defs if d.category != IndexCategory.LIFE.value]
|
||||
|
||||
async def mine(self, user: User) -> tuple[ErrorType, list[MyGak]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
|
||||
return err, rows or []
|
||||
|
||||
async def add(self, user: User, index_ids: list[int]) -> tuple[ErrorType, Optional[MyGak]]:
|
||||
a, b = sorted(index_ids)
|
||||
err, ok = await self.mixable()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if a == b or a not in ok or b not in ok:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count(s, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if n >= MAX_PER_USER:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, a, b))
|
||||
|
||||
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
|
||||
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
|
||||
@@ -0,0 +1,59 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from crud.index_crud import IndexCRUD
|
||||
from router.router import app
|
||||
from services.my_gak_service import MAX_PER_USER
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "섞기토끼"})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mixable_without_login_excludes_life_gak():
|
||||
async with client() as c:
|
||||
body = (await c.get("/v1/my-gak")).json()
|
||||
_, defs = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s))
|
||||
ids = {d.name: d.index_id for d in defs}
|
||||
assert body["items"] == []
|
||||
mixable = set(body["mixable"])
|
||||
assert {ids["러닝각"], ids["치맥각"]} <= mixable
|
||||
assert not {ids["우산각"], ids["교통체증각"]} & mixable
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_add_list_delete_and_same_pair_is_one():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/my-gak", json={"index_ids": [1, 2]})).status_code == 401
|
||||
h = await _login(c, "mix_01")
|
||||
a, b = sorted((await c.get("/v1/my-gak")).json()["mixable"])[:2]
|
||||
first = (await c.post("/v1/my-gak", json={"index_ids": [b, a]}, headers=h)).json()["item"]
|
||||
assert first["index_ids"] == [a, b]
|
||||
again = (await c.post("/v1/my-gak", json={"index_ids": [a, b]}, headers=h)).json()["item"]
|
||||
assert again["my_gak_id"] == first["my_gak_id"]
|
||||
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [first["my_gak_id"]]
|
||||
assert (await c.delete(f"/v1/my-gak/{first['my_gak_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert (await c.get("/v1/my-gak", headers=h)).json()["items"] == []
|
||||
assert (await c.delete(f"/v1/my-gak/{first['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_same_gak_unmixable_and_over_limit():
|
||||
async with client() as c:
|
||||
h = await _login(c, "mix_02")
|
||||
mixable = sorted((await c.get("/v1/my-gak")).json()["mixable"])
|
||||
bad = lambda ids: c.post("/v1/my-gak", json={"index_ids": ids}, headers=h) # noqa: E731
|
||||
assert (await bad([mixable[0], mixable[0]])).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await bad([mixable[0], 9999])).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await bad([mixable[0]])).status_code == 422
|
||||
pairs = [(mixable[0], x) for x in mixable[1 : MAX_PER_USER + 1]]
|
||||
for p in pairs:
|
||||
assert (await bad(list(p))).json()["item"]
|
||||
assert (await bad([mixable[1], mixable[2]])).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
@@ -3,8 +3,8 @@
|
||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
import { addComment, addMyGak, deleteComment, deleteMyGak, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
@@ -709,6 +709,58 @@ export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>)
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const listMyGakQueryKey = (options?: Options<ListMyGakData>) => createQueryKey('listMyGak', options);
|
||||
|
||||
/**
|
||||
* 내 각과 섞을 수 있는 공식 각 (로그인 없이도 섞을 수 있는 목록은 보임)
|
||||
*/
|
||||
export const listMyGakOptions = (options?: Options<ListMyGakData>) => queryOptions<ListMyGakResponse, ListMyGakError, ListMyGakResponse, ReturnType<typeof listMyGakQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listMyGak({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listMyGakQueryKey(options)
|
||||
});
|
||||
|
||||
/**
|
||||
* 공식 각 두 개를 섞어 내 각 만들기 (같은 조합이면 있는 것을 돌려줌)
|
||||
*/
|
||||
export const addMyGakMutation = (options?: Partial<Options<AddMyGakData>>): UseMutationOptions<AddMyGakResponse, AddMyGakError, Options<AddMyGakData>> => {
|
||||
const mutationOptions: UseMutationOptions<AddMyGakResponse, AddMyGakError, Options<AddMyGakData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await addMyGak({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 내 각 지우기
|
||||
*/
|
||||
export const deleteMyGakMutation = (options?: Partial<Options<DeleteMyGakData>>): UseMutationOptions<DeleteMyGakResponse, DeleteMyGakError, Options<DeleteMyGakData>> => {
|
||||
const mutationOptions: UseMutationOptions<DeleteMyGakResponse, DeleteMyGakError, Options<DeleteMyGakData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await deleteMyGak({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getWatchSummaryQueryKey = (options: Options<GetWatchSummaryData>) => createQueryKey('getWatchSummary', options);
|
||||
|
||||
/**
|
||||
@@ -745,6 +797,42 @@ export const getImageOptions = (options: Options<GetImageData>) => queryOptions<
|
||||
queryKey: getImageQueryKey(options)
|
||||
});
|
||||
|
||||
export const getTodayPageQueryKey = (options: Options<GetTodayPageData>) => createQueryKey('getTodayPage', options);
|
||||
|
||||
/**
|
||||
* 지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)
|
||||
*/
|
||||
export const getTodayPageOptions = (options: Options<GetTodayPageData>) => queryOptions<GetTodayPageResponse, GetTodayPageError, GetTodayPageResponse, ReturnType<typeof getTodayPageQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getTodayPage({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getTodayPageQueryKey(options)
|
||||
});
|
||||
|
||||
export const getTodayGuPageQueryKey = (options: Options<GetTodayGuPageData>) => createQueryKey('getTodayGuPage', options);
|
||||
|
||||
/**
|
||||
* 구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)
|
||||
*/
|
||||
export const getTodayGuPageOptions = (options: Options<GetTodayGuPageData>) => queryOptions<GetTodayGuPageResponse, GetTodayGuPageError, GetTodayGuPageResponse, ReturnType<typeof getTodayGuPageQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getTodayGuPage({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getTodayGuPageQueryKey(options)
|
||||
});
|
||||
|
||||
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, typeLine truncated
|
||||
export { addComment, addMyGak, deleteComment, deleteMyGak, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqMyGak, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek,
Line truncated
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||
/**
|
||||
@@ -218,6 +218,28 @@ export const unlikeComment = <ThrowOnError extends boolean = true>(options: Opti
|
||||
*/
|
||||
export const likeComment = <ThrowOnError extends boolean = true>(options: Options<LikeCommentData, ThrowOnError>): RequestResult<LikeCommentResponses, LikeCommentErrors, ThrowOnError> => (options.client ?? client).post<LikeCommentResponses, LikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 내 각과 섞을 수 있는 공식 각 (로그인 없이도 섞을 수 있는 목록은 보임)
|
||||
*/
|
||||
export const listMyGak = <ThrowOnError extends boolean = true>(options?: Options<ListMyGakData, ThrowOnError>): RequestResult<ListMyGakResponses, ListMyGakErrors, ThrowOnError> => (options?.client ?? client).get<ListMyGakResponses, ListMyGakErrors, ThrowOnError>({ url: '/v1/my-gak', ...options });
|
||||
|
||||
/**
|
||||
* 공식 각 두 개를 섞어 내 각 만들기 (같은 조합이면 있는 것을 돌려줌)
|
||||
*/
|
||||
export const addMyGak = <ThrowOnError extends boolean = true>(options: Options<AddMyGakData, ThrowOnError>): RequestResult<AddMyGakResponses, AddMyGakErrors, ThrowOnError> => (options.client ?? client).post<AddMyGakResponses, AddMyGakErrors, ThrowOnError>({
|
||||
url: '/v1/my-gak',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 내 각 지우기
|
||||
*/
|
||||
export const deleteMyGak = <ThrowOnError extends boolean = true>(options: Options<DeleteMyGakData, ThrowOnError>): RequestResult<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError> => (options.client ?? client).delete<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError>({ url: '/v1/my-gak/{my_gak_id}', ...options });
|
||||
|
||||
/**
|
||||
* 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표
|
||||
*/
|
||||
@@ -228,6 +250,16 @@ export const getWatchSummary = <ThrowOnError extends boolean = true>(options: Op
|
||||
*/
|
||||
export const getImage = <ThrowOnError extends boolean = true>(options: Options<GetImageData, ThrowOnError>): RequestResult<GetImageResponses, GetImageErrors, ThrowOnError> => (options.client ?? client).get<GetImageResponses, GetImageErrors, ThrowOnError>({ url: '/v1/image', ...options });
|
||||
|
||||
/**
|
||||
* 지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)
|
||||
*/
|
||||
export const getTodayPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayPageData, ThrowOnError>): RequestResult<GetTodayPageResponses, GetTodayPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayPageResponses, GetTodayPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}', ...options });
|
||||
|
||||
/**
|
||||
* 구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)
|
||||
*/
|
||||
export const getTodayGuPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayGuPageData, ThrowOnError>): RequestResult<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}/{gu}', ...options });
|
||||
|
||||
/**
|
||||
* 헬스체크
|
||||
*/
|
||||
|
||||
@@ -830,6 +830,22 @@ export type Me = {
|
||||
provider: AuthProvider;
|
||||
};
|
||||
|
||||
/**
|
||||
* MyGakData
|
||||
*/
|
||||
export type MyGakData = {
|
||||
/**
|
||||
* My Gak Id
|
||||
*/
|
||||
my_gak_id: number;
|
||||
/**
|
||||
* Index Ids
|
||||
*
|
||||
* 섞은 공식 각 두 개. 점수는 두 각의 오늘 점수 중 낮은 쪽
|
||||
*/
|
||||
index_ids: Array<number>;
|
||||
};
|
||||
|
||||
/**
|
||||
* PlaceData
|
||||
*/
|
||||
@@ -1219,6 +1235,21 @@ export type ReqLogin = {
|
||||
password: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_MyGak
|
||||
*/
|
||||
export type ReqMyGak = {
|
||||
/**
|
||||
* Index Ids
|
||||
*
|
||||
* 섞을 공식 각 두 개
|
||||
*/
|
||||
index_ids: [
|
||||
number,
|
||||
number
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_Refresh
|
||||
*/
|
||||
@@ -1535,6 +1566,41 @@ export type ResMe = {
|
||||
me?: Me | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_MyGak
|
||||
*/
|
||||
export type ResMyGak = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
item?: MyGakData | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_MyGakList
|
||||
*/
|
||||
export type ResMyGakList = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
/**
|
||||
* Mixable
|
||||
*
|
||||
* 섞을 수 있는 공식 각 index_id
|
||||
*/
|
||||
mixable?: Array<number>;
|
||||
/**
|
||||
* Items
|
||||
*
|
||||
* 내 각. 로그인하지 않았으면 비어 있음
|
||||
*/
|
||||
items?: Array<MyGakData>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_PlaceList
|
||||
*/
|
||||
@@ -2635,6 +2701,10 @@ export type WatchNow = {
|
||||
* Rain 2H
|
||||
*/
|
||||
rain_2h?: boolean | null;
|
||||
/**
|
||||
* Thunder
|
||||
*/
|
||||
thunder?: boolean | null;
|
||||
/**
|
||||
* Text
|
||||
*/
|
||||
@@ -3955,6 +4025,104 @@ export type LikeCommentResponses = {
|
||||
|
||||
export type LikeCommentResponse = LikeCommentResponses[keyof LikeCommentResponses];
|
||||
|
||||
export type ListMyGakData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/my-gak';
|
||||
};
|
||||
|
||||
export type ListMyGakErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type ListMyGakError = ListMyGakErrors[keyof ListMyGakErrors];
|
||||
|
||||
export type ListMyGakResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResMyGakList;
|
||||
};
|
||||
|
||||
export type ListMyGakResponse = ListMyGakResponses[keyof ListMyGakResponses];
|
||||
|
||||
export type AddMyGakData = {
|
||||
body: ReqMyGak;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/my-gak';
|
||||
};
|
||||
|
||||
export type AddMyGakErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type AddMyGakError = AddMyGakErrors[keyof AddMyGakErrors];
|
||||
|
||||
export type AddMyGakResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResMyGak;
|
||||
};
|
||||
|
||||
export type AddMyGakResponse = AddMyGakResponses[keyof AddMyGakResponses];
|
||||
|
||||
export type DeleteMyGakData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* My Gak Id
|
||||
*/
|
||||
my_gak_id: number;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/my-gak/{my_gak_id}';
|
||||
};
|
||||
|
||||
export type DeleteMyGakErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type DeleteMyGakError = DeleteMyGakErrors[keyof DeleteMyGakErrors];
|
||||
|
||||
export type DeleteMyGakResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResWebPacketProtocol;
|
||||
};
|
||||
|
||||
export type DeleteMyGakResponse = DeleteMyGakResponses[keyof DeleteMyGakResponses];
|
||||
|
||||
export type GetWatchSummaryData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
@@ -4031,6 +4199,78 @@ export type GetImageResponses = {
|
||||
200: unknown;
|
||||
};
|
||||
|
||||
export type GetTodayPageData = {
|
||||
body?: never;
|
||||
path: {
|
||||
/**
|
||||
* Sido
|
||||
*/
|
||||
sido: string;
|
||||
/**
|
||||
* Place
|
||||
*/
|
||||
place: string;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/seo/today/{sido}/{place}';
|
||||
};
|
||||
|
||||
export type GetTodayPageErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type GetTodayPageError = GetTodayPageErrors[keyof GetTodayPageErrors];
|
||||
|
||||
export type GetTodayPageResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: string;
|
||||
};
|
||||
|
||||
export type GetTodayPageResponse = GetTodayPageResponses[keyof GetTodayPageResponses];
|
||||
|
||||
export type GetTodayGuPageData = {
|
||||
body?: never;
|
||||
path: {
|
||||
/**
|
||||
* Sido
|
||||
*/
|
||||
sido: string;
|
||||
/**
|
||||
* Place
|
||||
*/
|
||||
place: string;
|
||||
/**
|
||||
* Gu
|
||||
*/
|
||||
gu: string;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/seo/today/{sido}/{place}/{gu}';
|
||||
};
|
||||
|
||||
export type GetTodayGuPageErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type GetTodayGuPageError = GetTodayGuPageErrors[keyof GetTodayGuPageErrors];
|
||||
|
||||
export type GetTodayGuPageResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: string;
|
||||
};
|
||||
|
||||
export type GetTodayGuPageResponse = GetTodayGuPageResponses[keyof GetTodayGuPageResponses];
|
||||
|
||||
export type HealthzHealthzGetData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
|
||||
@@ -25,6 +25,8 @@ import { track } from '../lib/analytics'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
import { MixSheet } from './myGak'
|
||||
import { useMyGak } from './myGakState'
|
||||
import { ownPage, useRegion } from './regionContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
@@ -102,7 +104,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
}, [isOpen])
|
||||
|
||||
const then = state?.type === 'login' ? state.then : undefined
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
|
||||
|
||||
return (
|
||||
<dialog
|
||||
@@ -132,6 +134,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
|
||||
{state.type === 'me' && <MeSheet onDone={onClose} />}
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
{state.type === 'mix' && <MixSheet ids={state.ids} shared={state.shared} onDone={onClose} />}
|
||||
</div>
|
||||
)}
|
||||
{!state && <RegionLinks />}
|
||||
@@ -323,6 +326,8 @@ function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[];
|
||||
|
||||
function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const { mixable } = useMyGak()
|
||||
const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } }))
|
||||
const d: ResIndexDetail | undefined = q.data
|
||||
const g = d?.index
|
||||
@@ -355,6 +360,11 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
|
||||
</div>
|
||||
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
|
||||
{mixable.has(g.index_id) && (
|
||||
<button type="button" onClick={() => open({ type: 'mix', ids: [g.index_id] })} className="mt-2.5 w-full cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
|
||||
다른 각과 섞어 내 각 만들기
|
||||
</button>
|
||||
)}
|
||||
{now && (
|
||||
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
|
||||
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/
|
||||
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
|
||||
import { MyGakRow } from './myGak'
|
||||
import { PostCard, PostCardSkel } from './Post'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
@@ -352,6 +353,7 @@ export function TodayPage() {
|
||||
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
||||
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
||||
const { preview } = useSky()
|
||||
const { open } = useSheet()
|
||||
const f = feed.data
|
||||
const posts = f?.posts ?? []
|
||||
const stories = atSlot(f?.stories ?? [], preview)
|
||||
@@ -364,6 +366,16 @@ export function TodayPage() {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [region.code])
|
||||
|
||||
// 친구가 보낸 섞은 각 링크(/?mix=3,8)로 들어오면 내 동네 기준으로 보여 준다
|
||||
useEffect(() => {
|
||||
const url = new URL(window.location.href)
|
||||
const ids = url.searchParams.get('mix')?.split(',').map(Number).filter(Number.isInteger)
|
||||
if (!ids || ids.length !== 2) return
|
||||
url.searchParams.delete('mix')
|
||||
window.history.replaceState(window.history.state, '', url)
|
||||
open({ type: 'mix', ids, shared: true })
|
||||
}, [open])
|
||||
|
||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [
|
||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
||||
@@ -375,6 +387,7 @@ export function TodayPage() {
|
||||
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
|
||||
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
||||
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<MyGakRow stories={f?.stories ?? []} />
|
||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
||||
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { getFeedOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { TopIndex } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { mix, shareUrl, useMyGak } from './myGakState'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, Sec } from './ui'
|
||||
|
||||
function Bar({ g, low }: { g: TopIndex; low: boolean }) {
|
||||
return (
|
||||
<span className="grid grid-cols-[1fr_auto] items-center gap-x-2 text-[12.5px] font-bold">
|
||||
<span>{g.name}</span>
|
||||
<em className={cx('font-jua not-italic', low ? 'text-(--ink2)' : 'text-(--orange)')}>{g.score}</em>
|
||||
<i className="col-span-2 block h-[7px] overflow-hidden rounded-full bg-[#e3eaf4]">
|
||||
<s className={cx('b-keep-bg block h-full', low ? 'bg-[#f3b38f]' : 'bg-(--orange)')} style={{ width: `${g.score}%` }} />
|
||||
</i>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 오늘 탭의 내 각 줄: 섞은 각 카드들과 새로 섞기 */
|
||||
export function MyGakRow({ stories }: { stories: TopIndex[] }) {
|
||||
const { open } = useSheet()
|
||||
const { pairs, remove } = useMyGak()
|
||||
const [copied, setCopied] = useState<string | null>(null)
|
||||
const send = (ids: number[], name: string) => {
|
||||
const url = shareUrl(ids)
|
||||
if (navigator.share) {
|
||||
navigator.share({ title: `${name} · 날씨각`, url }).catch((e: unknown) => {
|
||||
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
|
||||
})
|
||||
return
|
||||
}
|
||||
navigator.clipboard.writeText(url).then(
|
||||
() => setCopied(ids.join()),
|
||||
(e: unknown) => console.error('[myGak] copy', e),
|
||||
)
|
||||
}
|
||||
if (!stories.length) return null
|
||||
return (
|
||||
<>
|
||||
<Sec title="내 각" sub="공식 각 두 개를 섞어 만들어요. 둘 다 좋아야 높아요" />
|
||||
<div className="flex snap-x gap-2 overflow-x-auto px-3 pb-1 [scrollbar-width:none]">
|
||||
{pairs.map((p) => {
|
||||
const m = mix(stories, p.ids)
|
||||
if (!m) return null
|
||||
return (
|
||||
<div key={p.ids.join()} className="flex w-[220px] shrink-0 snap-start flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<div className="flex items-center gap-1">
|
||||
<Ic name={m.a.icon} className="w-8" />
|
||||
<Ic name={m.b.icon} className="-ml-3 w-8" />
|
||||
<b className="ml-1 font-jua text-[17px] leading-tight font-normal">{m.name}</b>
|
||||
<em className={cx('ml-auto font-bagel text-[28px] leading-none not-italic', m.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{m.score}</em>
|
||||
</div>
|
||||
<Bar g={m.a} low={m.low === m.a && m.a.score !== m.b.score} />
|
||||
<Bar g={m.b} low={m.low === m.b && m.a.score !== m.b.score} />
|
||||
<div className="mt-0.5 flex gap-1.5">
|
||||
<button type="button" onClick={() => send(p.ids, m.name)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
|
||||
{copied === p.ids.join() ? '링크 복사함' : '친구에게 보내기'}
|
||||
</button>
|
||||
<button type="button" onClick={() => remove(p)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)">
|
||||
지우기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] shrink-0 cursor-pointer snap-start flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
|
||||
<span className="text-[26px] leading-none">+</span>
|
||||
각 섞기
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** 섞을 각 고르기와 미리보기. ids 가 둘이면(받은 링크) 바로 미리보기 */
|
||||
export function MixSheet({ ids: start = [], shared = false, onDone }: { ids?: number[]; shared?: boolean; onDone: () => void }) {
|
||||
const { region } = useRegion()
|
||||
const stories = useQuery(getFeedOptions({ query: { region: region.code } })).data?.stories ?? []
|
||||
const { mixable, has, create, pending } = useMyGak()
|
||||
const [ids, setIds] = useState<number[]>(start.slice(0, 2))
|
||||
const choices = stories.filter((g) => mixable.has(g.index_id))
|
||||
const m = ids.length === 2 ? mix(stories, ids) : null
|
||||
const owned = ids.length === 2 && has(ids)
|
||||
const toggle = (id: number) => setIds((now) => (now.includes(id) ? now.filter((x) => x !== id) : now.length < 2 ? [...now, id] : [now[0], id]))
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
|
||||
{!shared && (
|
||||
<>
|
||||
<p className="m-0 font-jua text-[19px]">{ids.length === 2 ? '이 둘을 섞어요' : ids.length ? '하나 더 골라요' : '섞을 각 두 개를 골라요'}</p>
|
||||
<p className="mt-0.5 mb-2.5 text-[13px] font-semibold text-(--ink2)">함께 할 일끼리 골라요. 점수는 둘 중 낮은 쪽이에요</p>
|
||||
<div className="flex flex-wrap gap-1.5" role="group" aria-label="섞을 각">
|
||||
{choices.map((g) => {
|
||||
const on = ids.includes(g.index_id)
|
||||
return (
|
||||
<button key={g.index_id} type="button" aria-pressed={on} onClick={() => toggle(g.index_id)} className={cx('flex cursor-pointer items-center gap-1 rounded-full py-1 pr-3 pl-1.5 text-[13.5px] font-extrabold', on ? 'bg-(--orange) text-white' : 'bg-[#eef4fc] text-(--ink)')}>
|
||||
<Ic name={g.icon} className="w-6" />
|
||||
{g.name.replace(/각$/, '')}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{m && (
|
||||
<div className="mt-3.5 flex flex-col gap-2 rounded-[20px] bg-[#f3f6fb] p-3.5">
|
||||
{shared && <p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>}
|
||||
<div className="flex items-center gap-1">
|
||||
<Ic name={m.a.icon} className="w-9" />
|
||||
<Ic name={m.b.icon} className="-ml-3 w-9" />
|
||||
<b className="ml-1 font-jua text-[20px] font-normal">{m.name}</b>
|
||||
<em className={cx('ml-auto font-bagel text-[36px] leading-none not-italic', m.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{m.score}</em>
|
||||
</div>
|
||||
<Bar g={m.a} low={m.low === m.a && m.a.score !== m.b.score} />
|
||||
<Bar g={m.b} low={m.low === m.b && m.a.score !== m.b.score} />
|
||||
<p className="m-0 text-[13px] font-semibold text-(--ink2)">
|
||||
{m.a.score === m.b.score ? '두 각 점수가 같아요' : `오늘은 ${m.low.name} 점수를 따라가요`}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={!m || owned || pending}
|
||||
onClick={() => m && create(ids, onDone)}
|
||||
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
|
||||
>
|
||||
{owned ? '이미 내 각에 있어요' : shared ? '내 각으로 가져오기' : '내 각으로 만들기'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useSyncExternalStore } from 'react'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { TopIndex } from '../api/client/types.gen'
|
||||
import { useAuth } from './authContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
|
||||
const KEY = 'nalssigak.b.myGak'
|
||||
|
||||
/** 로그인하지 않으면 이 기기에 하나만 */
|
||||
export type Pair = { id?: number; ids: [number, number] }
|
||||
|
||||
const sameIds = (a: number[], b: number[]) => a.length === 2 && b.length === 2 && a[0] === b[0] && a[1] === b[1]
|
||||
const sorted = (ids: number[]) => [...ids].sort((x, y) => x - y) as [number, number]
|
||||
|
||||
function readLocal(): [number, number] | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY)
|
||||
return raw ? sorted(JSON.parse(raw) as number[]) : null
|
||||
} catch {
|
||||
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 시트와 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
|
||||
let local = readLocal()
|
||||
const listeners = new Set<() => void>()
|
||||
const subscribe = (cb: () => void) => {
|
||||
listeners.add(cb)
|
||||
return () => listeners.delete(cb)
|
||||
}
|
||||
|
||||
function setLocal(ids: [number, number] | null) {
|
||||
local = ids
|
||||
listeners.forEach((cb) => cb())
|
||||
try {
|
||||
if (ids) localStorage.setItem(KEY, JSON.stringify(ids))
|
||||
else localStorage.removeItem(KEY)
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 기기에 저장하지 못함', e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 두 각 이름을 이어 붙인 이름: 러닝각 + 치맥각 → 러닝·치맥각 */
|
||||
const pairName = (a: TopIndex, b: TopIndex) => `${a.name.replace(/각$/, '')}·${b.name}`
|
||||
|
||||
/** 섞은 각 점수: 둘 다 좋아야 좋은 날이라 낮은 쪽 */
|
||||
export function mix(stories: TopIndex[], ids: number[]) {
|
||||
const a = stories.find((g) => g.index_id === ids[0])
|
||||
const b = stories.find((g) => g.index_id === ids[1])
|
||||
if (!a || !b) return null
|
||||
return { a, b, name: pairName(a, b), score: Math.min(a.score, b.score), low: a.score <= b.score ? a : b }
|
||||
}
|
||||
|
||||
export const shareUrl = (ids: number[]) => `${SITE_URL}/?mix=${ids.join(',')}`
|
||||
|
||||
export function useMyGak() {
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const queryClient = useQueryClient()
|
||||
const q = useQuery(listMyGakOptions())
|
||||
const saved = useSyncExternalStore(subscribe, () => local)
|
||||
const add = useMutation({ ...addMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
|
||||
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
|
||||
|
||||
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
|
||||
const { mutate } = add
|
||||
useEffect(() => {
|
||||
if (!loggedIn || !saved) return
|
||||
mutate({ body: { index_ids: saved } }, { onSuccess: () => setLocal(null) })
|
||||
}, [loggedIn, saved, mutate])
|
||||
|
||||
const pairs: Pair[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, ids: sorted(g.index_ids) })) : saved ? [{ ids: saved }] : []
|
||||
const has = (ids: number[]) => pairs.some((p) => sameIds(p.ids, sorted(ids)))
|
||||
|
||||
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
|
||||
const create = (ids: number[], onDone?: () => void) => {
|
||||
const two = sorted(ids)
|
||||
if (loggedIn) {
|
||||
add.mutate({ body: { index_ids: two } }, { onSuccess: onDone })
|
||||
return
|
||||
}
|
||||
if (saved && !sameIds(saved, two)) {
|
||||
open({ type: 'login' })
|
||||
return
|
||||
}
|
||||
setLocal(two)
|
||||
onDone?.()
|
||||
}
|
||||
|
||||
const remove = (p: Pair) => {
|
||||
if (p.id != null) return del.mutate({ path: { my_gak_id: p.id } })
|
||||
setLocal(null)
|
||||
}
|
||||
|
||||
return { mixable: new Set(q.data?.mixable ?? []), pairs, has, create, remove, pending: add.isPending }
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export type SheetState =
|
||||
| { type: 'login'; then?: CommentsState }
|
||||
| { type: 'me' }
|
||||
| { type: 'region' }
|
||||
| { type: 'mix'; ids?: number[]; shared?: boolean }
|
||||
| null
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
|
||||
|
||||
Reference in new issue
Block a user