feat: 동네 이야기 — 로그인하면 100자 글 쓰기(쓸 때 동네 날씨가 붙음, 전국에 보임), 좋아요·신고 3건 자동 숨김·이 사람 글 안 보기·내 글 지우기, 링크·전화번호 막기와 하루 5개 제한
This commit is contained in:
1 parent
a8a126f6a5
commit
798286d975
18 files changed
+1356
-6
No files matched your search
@@ -372,3 +372,43 @@ class MyGak(Base):
|
||||
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())
|
||||
|
||||
|
||||
class Talk(Base):
|
||||
__tablename__ = "talk"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
region_code: Mapped[str] = mapped_column(String(10))
|
||||
body: Mapped[str] = mapped_column(String(100))
|
||||
weather: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
hidden: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class TalkLike(Base):
|
||||
__tablename__ = "talk_like"
|
||||
|
||||
talk_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 TalkReport(Base):
|
||||
__tablename__ = "talk_report"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
reason: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class UserBlock(Base):
|
||||
__tablename__ = "user_block"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
blocked_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())
|
||||
@@ -19,6 +19,8 @@ class ErrorType(Enum):
|
||||
EXTERNAL_API_ERROR = 2001
|
||||
NOT_FOUND = 3001
|
||||
INVALID_INPUT = 3002
|
||||
DAILY_LIMIT = 3003 # 하루에 쓸 수 있는 수를 넘음
|
||||
LINK_NOT_ALLOWED = 3004 # 글에 링크·전화번호
|
||||
AUTH_REQUIRED = 4001
|
||||
AUTH_FAILED = 4002
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
@@ -113,6 +115,13 @@ class IndexCategory(CodeEnum):
|
||||
LIFE = 4
|
||||
|
||||
|
||||
class TalkReport(CodeEnum):
|
||||
ABUSE = 1 # 욕설·비하
|
||||
SPAM = 2 # 광고·도배
|
||||
PRIVACY = 3 # 개인정보 노출
|
||||
ETC = 4
|
||||
|
||||
|
||||
class ArticleCategory(CodeEnum):
|
||||
SEASON = 1
|
||||
TIP = 2
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Region, Talk, TalkLike, TalkReport, User, UserBlock
|
||||
|
||||
|
||||
class TalkCRUD:
|
||||
async def page(self, s: AsyncSession, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Talk, User, Optional[str]]]:
|
||||
"""최신 글부터. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다."""
|
||||
stmt = (
|
||||
select(Talk, User, Region.short_name)
|
||||
.join(User, User.user_id == Talk.user_id)
|
||||
.outerjoin(Region, Region.code == Talk.region_code)
|
||||
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False))
|
||||
)
|
||||
if viewer is not None:
|
||||
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(Talk.talk_id < cursor)
|
||||
return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all())
|
||||
|
||||
async def liked(self, s: AsyncSession, user_id: uuid.UUID, talk_ids: list[int]) -> set[int]:
|
||||
return set((await s.scalars(select(TalkLike.talk_id).where(TalkLike.user_id == user_id, TalkLike.talk_id.in_(talk_ids)))).all())
|
||||
|
||||
async def count_since(self, s: AsyncSession, user_id: uuid.UUID, since: datetime) -> int:
|
||||
return await s.scalar(select(func.count()).select_from(Talk).where(Talk.user_id == user_id, Talk.created_at >= since))
|
||||
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str]) -> Talk:
|
||||
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather)
|
||||
s.add(t)
|
||||
await s.flush()
|
||||
await s.refresh(t)
|
||||
return t
|
||||
|
||||
async def get(self, s: AsyncSession, talk_id: int) -> Optional[Talk]:
|
||||
return await s.scalar(select(Talk).where(Talk.talk_id == talk_id, Talk.deleted.is_(False)))
|
||||
|
||||
async def delete(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID) -> bool:
|
||||
res = await s.execute(update(Talk).where(Talk.talk_id == talk_id, Talk.user_id == user_id, Talk.deleted.is_(False)).values(deleted=True).returning(Talk.talk_id))
|
||||
return res.first() is not None
|
||||
|
||||
async def toggle_like(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, on: bool) -> int:
|
||||
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
|
||||
if on:
|
||||
res = await s.execute(insert(TalkLike).values(talk_id=talk_id, user_id=user_id).on_conflict_do_nothing().returning(TalkLike.talk_id))
|
||||
else:
|
||||
res = await s.execute(delete(TalkLike).where(TalkLike.talk_id == talk_id, TalkLike.user_id == user_id).returning(TalkLike.talk_id))
|
||||
if res.first() is not None:
|
||||
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(like_count=Talk.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Talk.like_count).where(Talk.talk_id == talk_id))
|
||||
|
||||
async def report(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, reason: int, hide_at: int) -> None:
|
||||
"""한 사람은 한 번만 센다. hide_at 건이 되면 숨긴다."""
|
||||
res = await s.execute(insert(TalkReport).values(talk_id=talk_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(TalkReport.talk_id))
|
||||
if res.first() is None:
|
||||
return
|
||||
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(report_count=Talk.report_count + 1, hidden=Talk.report_count + 1 >= hide_at))
|
||||
|
||||
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
|
||||
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
|
||||
@@ -259,6 +259,45 @@ CREATE TABLE IF NOT EXISTS public.my_gak (
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_my_gak ON public.my_gak (user_id, index_a, index_b);
|
||||
|
||||
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
|
||||
CREATE TABLE IF NOT EXISTS public.talk (
|
||||
talk_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
body VARCHAR(100) NOT NULL,
|
||||
weather VARCHAR(30), -- 쓸 때 날씨 한 줄 (예: 18° 맑음)
|
||||
like_count INTEGER NOT NULL DEFAULT 0,
|
||||
report_count INTEGER NOT NULL DEFAULT 0, -- 로그인한 사람의 신고만 센다
|
||||
hidden BOOLEAN NOT NULL DEFAULT FALSE, -- 신고가 쌓이면 자동으로 숨김
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_talk_list ON public.talk (talk_id DESC) WHERE deleted = FALSE AND hidden = FALSE;
|
||||
CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_like (
|
||||
talk_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_report (
|
||||
talk_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
reason SMALLINT NOT NULL, -- TalkReport: 1=욕설·비하 2=광고·도배 3=개인정보 노출 4=기타
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, user_id)
|
||||
);
|
||||
|
||||
-- 이 사람 글 안 보기
|
||||
CREATE TABLE IF NOT EXISTS public.user_block (
|
||||
user_id UUID NOT NULL,
|
||||
blocked_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, blocked_id)
|
||||
);
|
||||
|
||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||
|
||||
-- 구 목록.
|
||||
|
||||
@@ -17,6 +17,7 @@ from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
from router.v1.seo.seo import router as seo_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.talk.talk import router as talk_router
|
||||
from router.v1.watch.watch import router as watch_router
|
||||
from router.v1.weather.weather import router as weather_router
|
||||
from router.v1.week.week import router as week_router
|
||||
@@ -44,6 +45,7 @@ app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(my_gak_router)
|
||||
app.include_router(talk_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
app.include_router(seo_router)
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,45 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import TalkReport
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class TalkData(WebPacketProtocol):
|
||||
talk_id: int
|
||||
nickname: str
|
||||
character: str
|
||||
color: str
|
||||
mood: Optional[str] = None
|
||||
region_name: Optional[str] = Field(None, description="쓴 사람이 고른 동네 (성남시 분당구)")
|
||||
weather: Optional[str] = Field(None, description="쓸 때 그 동네 날씨 (18° 맑음)")
|
||||
body: str
|
||||
like_count: int
|
||||
liked: bool
|
||||
mine: bool
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Req_Talk(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
body: str = Field(min_length=1, max_length=200, description="공백을 줄인 뒤 100자까지")
|
||||
|
||||
|
||||
class Req_TalkReport(Req_WebPacketProtocol):
|
||||
reason: TalkReport
|
||||
|
||||
|
||||
class Res_TalkList(Res_WebPacketProtocol):
|
||||
talks: list[TalkData] = []
|
||||
next_cursor: Optional[int] = None
|
||||
|
||||
|
||||
class Res_Talk(Res_WebPacketProtocol):
|
||||
talk: Optional[TalkData] = None
|
||||
|
||||
|
||||
class Res_TalkLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
@@ -0,0 +1,67 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from common.utils.kma_time import KST
|
||||
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkLike, Res_TalkList, TalkData
|
||||
from services.talk_service import PAGE, TalkService, TalkView
|
||||
|
||||
router = APIRouter(prefix="/v1/talk", tags=["talk"])
|
||||
|
||||
|
||||
def _data(v: TalkView) -> TalkData:
|
||||
t, u = v.talk, v.author
|
||||
return TalkData(
|
||||
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
|
||||
body=t.body, like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국, 최신순, 로그인 없이 보기)")
|
||||
async def list_talks(cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), service: TalkService = Depends()) -> Res_TalkList:
|
||||
err, views = await service.page(user, cursor)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_TalkList(result=error_info(err))
|
||||
talks = [_data(v) for v in views]
|
||||
return Res_TalkList(talks=talks, next_cursor=talks[-1].talk_id if len(talks) == PAGE else None)
|
||||
|
||||
|
||||
@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)")
|
||||
async def add_talk(req: Req_Talk, user: User = Depends(current_user), service: TalkService = Depends()) -> Res_Talk:
|
||||
err, v = await service.add(user, req.region_code, req.body)
|
||||
return Res_Talk(result=error_info(err)) if err is not ErrorType.SUCCESS or v is None else Res_Talk(talk=_data(v))
|
||||
|
||||
|
||||
@router.delete("/{talk_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 이야기 지우기")
|
||||
async def delete_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete(user, talk_id)))
|
||||
|
||||
|
||||
async def _like(talk_id: int, user: User, on: bool, service: TalkService) -> Res_TalkLike:
|
||||
err, count = await service.like(user, talk_id, on)
|
||||
return Res_TalkLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요")
|
||||
async def like_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_TalkLike:
|
||||
return await _like(talk_id, user, True, service)
|
||||
|
||||
|
||||
@router.delete("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 취소")
|
||||
async def unlike_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_TalkLike:
|
||||
return await _like(talk_id, user, False, service)
|
||||
|
||||
|
||||
@router.post("/{talk_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이야기 신고 (서로 다른 3명이면 숨김)")
|
||||
async def report_talk(req: Req_TalkReport, talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.report(user, talk_id, req.reason)))
|
||||
|
||||
|
||||
@router.post("/{talk_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 글 쓴 사람의 글 안 보기")
|
||||
async def block_talk_author(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.block_author(user, talk_id)))
|
||||
@@ -0,0 +1,129 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Talk, User, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky, TalkReport
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.talk_crud import TalkCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
|
||||
BODY_MAX = 100
|
||||
DAILY_MAX = 5
|
||||
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
|
||||
HIDE_AT = 3
|
||||
PAGE = 20
|
||||
|
||||
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
|
||||
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
|
||||
_PHONE = re.compile(r"0\d{1,2}[-.\s]?\d{3,4}[-.\s]?\d{4}")
|
||||
|
||||
_SKY = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
def weather_line(row: Optional[WeatherHourly]) -> Optional[str]:
|
||||
"""글에 붙일 그때 날씨: 18° 맑음 / 12° 비."""
|
||||
if row is None:
|
||||
return None
|
||||
rain = RainType(row.rain_type)
|
||||
word = _RAIN.get(rain) or _SKY.get(Sky(row.sky), "")
|
||||
return f"{round(float(row.temp_c))}° {word}".strip()
|
||||
|
||||
|
||||
@dataclass
|
||||
class TalkView:
|
||||
talk: Talk
|
||||
author: User
|
||||
region_name: Optional[str]
|
||||
liked: bool
|
||||
mine: bool
|
||||
|
||||
|
||||
class TalkService:
|
||||
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
|
||||
self.crud, self.regions, self.weather = crud, regions, weather
|
||||
|
||||
async def page(self, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[TalkView]]:
|
||||
viewer = user.user_id if user else None
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, cursor, PAGE))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
if user is not None and rows:
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, [t.talk_id for t, *_ in rows]))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
return ErrorType.SUCCESS, [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows]
|
||||
|
||||
async def _weather_now(self, region_code: str) -> Optional[str]:
|
||||
"""지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다."""
|
||||
now = now_kst()
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region_code, now - timedelta(hours=1), now + timedelta(hours=2)))
|
||||
if err is not ErrorType.SUCCESS or not rows:
|
||||
return None
|
||||
return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now)))
|
||||
|
||||
async def add(self, user: User, region_code: str, body: str) -> tuple[ErrorType, Optional[TalkView]]:
|
||||
body = " ".join(body.split())
|
||||
if not body or len(body) > BODY_MAX:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if _LINK.search(body) or _PHONE.search(body):
|
||||
return ErrorType.LINK_NOT_ALLOWED, None
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if region is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
today = kst_midnight(now_kst().date())
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count_since(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if n >= DAILY_MAX:
|
||||
return ErrorType.DAILY_LIMIT, None
|
||||
weather = await self._weather_now(region_code)
|
||||
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather))
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
|
||||
|
||||
async def delete(self, user: User, talk_id: int) -> ErrorType:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, talk_id, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def _talk(self, talk_id: int) -> tuple[ErrorType, Optional[Talk]]:
|
||||
err, t = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, talk_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.SUCCESS, t) if t is not None else (ErrorType.NOT_FOUND, None)
|
||||
|
||||
async def like(self, user: User, talk_id: int, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, _ = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_like(s, talk_id, user.user_id, on))
|
||||
|
||||
async def report(self, user: User, talk_id: int, reason: TalkReport) -> ErrorType:
|
||||
err, t = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err
|
||||
if t.user_id == user.user_id:
|
||||
return ErrorType.INVALID_INPUT
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.report(s, talk_id, user.user_id, reason.value, HIDE_AT))
|
||||
return err
|
||||
|
||||
async def block_author(self, user: User, talk_id: int) -> ErrorType:
|
||||
err, t = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err
|
||||
if t.user_id == user.user_id:
|
||||
return ErrorType.INVALID_INPUT
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.block(s, user.user_id, t.user_id))
|
||||
return err
|
||||
@@ -0,0 +1,89 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
from services.talk_service import DAILY_MAX, HIDE_AT, weather_line
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
|
||||
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": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
async def _write(c, h, body="망원동 하늘 진짜 맑아요"):
|
||||
return (await c.post("/v1/talk", json={"region_code": REGION, "body": body}, headers=h)).json()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_write_list_like_delete():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕"})).status_code == 401
|
||||
h = await _login(c, "talk_01")
|
||||
t = (await _write(c, h, " 바람 많이 불어요 "))["talk"]
|
||||
assert t["body"] == "바람 많이 불어요" and t["mine"] is True and t["region_name"]
|
||||
|
||||
anon = (await c.get("/v1/talk/list")).json()["talks"]
|
||||
mine = next(x for x in anon if x["talk_id"] == t["talk_id"])
|
||||
assert mine["mine"] is False and mine["nickname"] == "talk_01"
|
||||
|
||||
liked = (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()
|
||||
assert liked["liked"] is True and liked["like_count"] == 1
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 1
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 0
|
||||
|
||||
other = await _login(c, "talk_02")
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=other)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_links_phone_long_and_daily_limit():
|
||||
async with client() as c:
|
||||
h = await _login(c, "talk_03")
|
||||
assert (await _write(c, h, "여기 보세요 https://spam.example"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "연락 주세요 010-1234-5678"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "가" * 101))["result"]["desc"] == "INVALID_INPUT"
|
||||
bad_region = (await c.post("/v1/talk", json={"region_code": "0000000000", "body": "안녕"}, headers=h)).json()
|
||||
assert bad_region["result"]["desc"] == "INVALID_INPUT"
|
||||
for i in range(DAILY_MAX):
|
||||
assert (await _write(c, h, f"오늘 {i}번째"))["talk"]
|
||||
assert (await _write(c, h))["result"]["desc"] == "DAILY_LIMIT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reports_hide_and_block_hides_author():
|
||||
async with client() as c:
|
||||
author = await _login(c, "talk_04")
|
||||
t = (await _write(c, author))["talk"]
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 1}, headers=author)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
viewer = await _login(c, "talk_05")
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/block", headers=viewer)).json()["result"]["success"] is True
|
||||
seen = [x["talk_id"] for x in (await c.get("/v1/talk/list", headers=viewer)).json()["talks"]]
|
||||
assert t["talk_id"] not in seen
|
||||
assert t["talk_id"] in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
for i in range(HIDE_AT):
|
||||
h = await _login(c, f"talk_r{i}")
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
def test_weather_line():
|
||||
class Row:
|
||||
temp_c, sky, rain_type = 18.4, 1, 1
|
||||
|
||||
class Wet:
|
||||
temp_c, sky, rain_type = 11.6, 3, 2
|
||||
|
||||
assert weather_line(Row()) == "18° 맑음"
|
||||
assert weather_line(Wet()) == "12° 비"
|
||||
assert weather_line(None) is None
|
||||
@@ -3,8 +3,8 @@
|
||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.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';
|
||||
import { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, 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, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
@@ -761,6 +761,156 @@ export const deleteMyGakMutation = (options?: Partial<Options<DeleteMyGakData>>)
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const listTalksQueryKey = (options?: Options<ListTalksData>) => createQueryKey('listTalks', options);
|
||||
|
||||
/**
|
||||
* 동네 이야기 (전국, 최신순, 로그인 없이 보기)
|
||||
*/
|
||||
export const listTalksOptions = (options?: Options<ListTalksData>) => queryOptions<ListTalksResponse, ListTalksError, ListTalksResponse, ReturnType<typeof listTalksQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listTalks({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listTalksQueryKey(options)
|
||||
});
|
||||
|
||||
export const listTalksInfiniteQueryKey = (options?: Options<ListTalksData>): QueryKey<Options<ListTalksData>> => createQueryKey('listTalks', options, true);
|
||||
|
||||
/**
|
||||
* 동네 이야기 (전국, 최신순, 로그인 없이 보기)
|
||||
*/
|
||||
export const listTalksInfiniteOptions = (options?: Options<ListTalksData>) => {
|
||||
const opts = infiniteQueryOptions<ListTalksResponse, ListTalksError, InfiniteData<ListTalksResponse>, QueryKey<Options<ListTalksData>>, number | null | Pick<QueryKey<Options<ListTalksData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
|
||||
// @ts-ignore
|
||||
{
|
||||
queryFn: async ({ pageParam, queryKey, signal }) => {
|
||||
// @ts-ignore
|
||||
const page: Pick<QueryKey<Options<ListTalksData>>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : {
|
||||
query: {
|
||||
cursor: pageParam
|
||||
}
|
||||
};
|
||||
const params = createInfiniteParams(queryKey, page);
|
||||
const { data } = await listTalks({
|
||||
...options,
|
||||
...params,
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listTalksInfiniteQueryKey(options)
|
||||
});
|
||||
return opts as Omit<typeof opts, 'initialData'>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)
|
||||
*/
|
||||
export const addTalkMutation = (options?: Partial<Options<AddTalkData>>): UseMutationOptions<AddTalkResponse, AddTalkError, Options<AddTalkData>> => {
|
||||
const mutationOptions: UseMutationOptions<AddTalkResponse, AddTalkError, Options<AddTalkData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await addTalk({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 내 이야기 지우기
|
||||
*/
|
||||
export const deleteTalkMutation = (options?: Partial<Options<DeleteTalkData>>): UseMutationOptions<DeleteTalkResponse, DeleteTalkError, Options<DeleteTalkData>> => {
|
||||
const mutationOptions: UseMutationOptions<DeleteTalkResponse, DeleteTalkError, Options<DeleteTalkData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await deleteTalk({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 이야기 좋아요 취소
|
||||
*/
|
||||
export const unlikeTalkMutation = (options?: Partial<Options<UnlikeTalkData>>): UseMutationOptions<UnlikeTalkResponse, UnlikeTalkError, Options<UnlikeTalkData>> => {
|
||||
const mutationOptions: UseMutationOptions<UnlikeTalkResponse, UnlikeTalkError, Options<UnlikeTalkData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await unlikeTalk({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 이야기 좋아요
|
||||
*/
|
||||
export const likeTalkMutation = (options?: Partial<Options<LikeTalkData>>): UseMutationOptions<LikeTalkResponse, LikeTalkError, Options<LikeTalkData>> => {
|
||||
const mutationOptions: UseMutationOptions<LikeTalkResponse, LikeTalkError, Options<LikeTalkData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await likeTalk({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 이야기 신고 (서로 다른 3명이면 숨김)
|
||||
*/
|
||||
export const reportTalkMutation = (options?: Partial<Options<ReportTalkData>>): UseMutationOptions<ReportTalkResponse, ReportTalkError, Options<ReportTalkData>> => {
|
||||
const mutationOptions: UseMutationOptions<ReportTalkResponse, ReportTalkError, Options<ReportTalkData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await reportTalk({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 이 글 쓴 사람의 글 안 보기
|
||||
*/
|
||||
export const blockTalkAuthorMutation = (options?: Partial<Options<BlockTalkAuthorData>>): UseMutationOptions<BlockTalkAuthorResponse, BlockTalkAuthorError, Options<BlockTalkAuthorData>> => {
|
||||
const mutationOptions: UseMutationOptions<BlockTalkAuthorResponse, BlockTalkAuthorError, Options<BlockTalkAuthorData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await blockTalkAuthor({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getWatchSummaryQueryKey = (options: Options<GetWatchSummaryData>) => createQueryKey('getWatchSummary', options);
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
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
|
||||
export { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, signup, unlikeComment, unlikePost, unlikeTalk, 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 AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, 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 DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, 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 LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, 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 ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, 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 RLine 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, 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';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, 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, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, 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> & {
|
||||
/**
|
||||
@@ -240,6 +240,55 @@ export const addMyGak = <ThrowOnError extends boolean = true>(options: Options<A
|
||||
*/
|
||||
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 });
|
||||
|
||||
/**
|
||||
* 동네 이야기 (전국, 최신순, 로그인 없이 보기)
|
||||
*/
|
||||
export const listTalks = <ThrowOnError extends boolean = true>(options?: Options<ListTalksData, ThrowOnError>): RequestResult<ListTalksResponses, ListTalksErrors, ThrowOnError> => (options?.client ?? client).get<ListTalksResponses, ListTalksErrors, ThrowOnError>({ url: '/v1/talk/list', ...options });
|
||||
|
||||
/**
|
||||
* 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)
|
||||
*/
|
||||
export const addTalk = <ThrowOnError extends boolean = true>(options: Options<AddTalkData, ThrowOnError>): RequestResult<AddTalkResponses, AddTalkErrors, ThrowOnError> => (options.client ?? client).post<AddTalkResponses, AddTalkErrors, ThrowOnError>({
|
||||
url: '/v1/talk',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 내 이야기 지우기
|
||||
*/
|
||||
export const deleteTalk = <ThrowOnError extends boolean = true>(options: Options<DeleteTalkData, ThrowOnError>): RequestResult<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError> => (options.client ?? client).delete<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}', ...options });
|
||||
|
||||
/**
|
||||
* 이야기 좋아요 취소
|
||||
*/
|
||||
export const unlikeTalk = <ThrowOnError extends boolean = true>(options: Options<UnlikeTalkData, ThrowOnError>): RequestResult<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError> => (options.client ?? client).delete<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 이야기 좋아요
|
||||
*/
|
||||
export const likeTalk = <ThrowOnError extends boolean = true>(options: Options<LikeTalkData, ThrowOnError>): RequestResult<LikeTalkResponses, LikeTalkErrors, ThrowOnError> => (options.client ?? client).post<LikeTalkResponses, LikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 이야기 신고 (서로 다른 3명이면 숨김)
|
||||
*/
|
||||
export const reportTalk = <ThrowOnError extends boolean = true>(options: Options<ReportTalkData, ThrowOnError>): RequestResult<ReportTalkResponses, ReportTalkErrors, ThrowOnError> => (options.client ?? client).post<ReportTalkResponses, ReportTalkErrors, ThrowOnError>({
|
||||
url: '/v1/talk/{talk_id}/report',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 이 글 쓴 사람의 글 안 보기
|
||||
*/
|
||||
export const blockTalkAuthor = <ThrowOnError extends boolean = true>(options: Options<BlockTalkAuthorData, ThrowOnError>): RequestResult<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError> => (options.client ?? client).post<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/block', ...options });
|
||||
|
||||
/**
|
||||
* 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표
|
||||
*/
|
||||
|
||||
@@ -1278,6 +1278,29 @@ export type ReqSignup = {
|
||||
nickname: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_Talk
|
||||
*/
|
||||
export type ReqTalk = {
|
||||
/**
|
||||
* Region Code
|
||||
*/
|
||||
region_code: string;
|
||||
/**
|
||||
* Body
|
||||
*
|
||||
* 공백을 줄인 뒤 100자까지
|
||||
*/
|
||||
body: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_TalkReport
|
||||
*/
|
||||
export type ReqTalkReport = {
|
||||
reason: TalkReport;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_UpdateMe
|
||||
*/
|
||||
@@ -1826,6 +1849,56 @@ export type ResSkyRanking = {
|
||||
items?: Array<RankData>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_Talk
|
||||
*/
|
||||
export type ResTalk = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
talk?: TalkData | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_TalkLike
|
||||
*/
|
||||
export type ResTalkLike = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
/**
|
||||
* Liked
|
||||
*/
|
||||
liked?: boolean | null;
|
||||
/**
|
||||
* Like Count
|
||||
*/
|
||||
like_count?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_TalkList
|
||||
*/
|
||||
export type ResTalkList = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
/**
|
||||
* Talks
|
||||
*/
|
||||
talks?: Array<TalkData>;
|
||||
/**
|
||||
* Next Cursor
|
||||
*/
|
||||
next_cursor?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_WatchSummary
|
||||
*/
|
||||
@@ -2431,6 +2504,91 @@ export type SunsetSlide = {
|
||||
peak_at?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* TalkData
|
||||
*/
|
||||
export type TalkData = {
|
||||
/**
|
||||
* Talk Id
|
||||
*/
|
||||
talk_id: number;
|
||||
/**
|
||||
* Nickname
|
||||
*/
|
||||
nickname: string;
|
||||
/**
|
||||
* Character
|
||||
*/
|
||||
character: string;
|
||||
/**
|
||||
* Color
|
||||
*/
|
||||
color: string;
|
||||
/**
|
||||
* Mood
|
||||
*/
|
||||
mood?: string | null;
|
||||
/**
|
||||
* Region Name
|
||||
*
|
||||
* 쓴 사람이 고른 동네 (성남시 분당구)
|
||||
*/
|
||||
region_name?: string | null;
|
||||
/**
|
||||
* Weather
|
||||
*
|
||||
* 쓸 때 그 동네 날씨 (18° 맑음)
|
||||
*/
|
||||
weather?: string | null;
|
||||
/**
|
||||
* Body
|
||||
*/
|
||||
body: string;
|
||||
/**
|
||||
* Like Count
|
||||
*/
|
||||
like_count: number;
|
||||
/**
|
||||
* Liked
|
||||
*/
|
||||
liked: boolean;
|
||||
/**
|
||||
* Mine
|
||||
*/
|
||||
mine: boolean;
|
||||
/**
|
||||
* Created At
|
||||
*/
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* TalkReport
|
||||
*/
|
||||
export const TalkReport = {
|
||||
/**
|
||||
* ABUSE
|
||||
*/
|
||||
ABUSE: 1,
|
||||
/**
|
||||
* SPAM
|
||||
*/
|
||||
SPAM: 2,
|
||||
/**
|
||||
* PRIVACY
|
||||
*/
|
||||
PRIVACY: 3,
|
||||
/**
|
||||
* ETC
|
||||
*/
|
||||
ETC: 4
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* TalkReport
|
||||
*/
|
||||
export type TalkReport = typeof TalkReport[keyof typeof TalkReport];
|
||||
|
||||
/**
|
||||
* TermData
|
||||
*/
|
||||
@@ -4123,6 +4281,253 @@ export type DeleteMyGakResponses = {
|
||||
|
||||
export type DeleteMyGakResponse = DeleteMyGakResponses[keyof DeleteMyGakResponses];
|
||||
|
||||
export type ListTalksData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path?: never;
|
||||
query?: {
|
||||
/**
|
||||
* Cursor
|
||||
*/
|
||||
cursor?: number | null;
|
||||
};
|
||||
url: '/v1/talk/list';
|
||||
};
|
||||
|
||||
export type ListTalksErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type ListTalksError = ListTalksErrors[keyof ListTalksErrors];
|
||||
|
||||
export type ListTalksResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResTalkList;
|
||||
};
|
||||
|
||||
export type ListTalksResponse = ListTalksResponses[keyof ListTalksResponses];
|
||||
|
||||
export type AddTalkData = {
|
||||
body: ReqTalk;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/talk';
|
||||
};
|
||||
|
||||
export type AddTalkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type AddTalkError = AddTalkErrors[keyof AddTalkErrors];
|
||||
|
||||
export type AddTalkResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResTalk;
|
||||
};
|
||||
|
||||
export type AddTalkResponse = AddTalkResponses[keyof AddTalkResponses];
|
||||
|
||||
export type DeleteTalkData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* Talk Id
|
||||
*/
|
||||
talk_id: number;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/talk/{talk_id}';
|
||||
};
|
||||
|
||||
export type DeleteTalkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type DeleteTalkError = DeleteTalkErrors[keyof DeleteTalkErrors];
|
||||
|
||||
export type DeleteTalkResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResWebPacketProtocol;
|
||||
};
|
||||
|
||||
export type DeleteTalkResponse = DeleteTalkResponses[keyof DeleteTalkResponses];
|
||||
|
||||
export type UnlikeTalkData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* Talk Id
|
||||
*/
|
||||
talk_id: number;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/talk/{talk_id}/like';
|
||||
};
|
||||
|
||||
export type UnlikeTalkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type UnlikeTalkError = UnlikeTalkErrors[keyof UnlikeTalkErrors];
|
||||
|
||||
export type UnlikeTalkResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResTalkLike;
|
||||
};
|
||||
|
||||
export type UnlikeTalkResponse = UnlikeTalkResponses[keyof UnlikeTalkResponses];
|
||||
|
||||
export type LikeTalkData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* Talk Id
|
||||
*/
|
||||
talk_id: number;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/talk/{talk_id}/like';
|
||||
};
|
||||
|
||||
export type LikeTalkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type LikeTalkError = LikeTalkErrors[keyof LikeTalkErrors];
|
||||
|
||||
export type LikeTalkResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResTalkLike;
|
||||
};
|
||||
|
||||
export type LikeTalkResponse = LikeTalkResponses[keyof LikeTalkResponses];
|
||||
|
||||
export type ReportTalkData = {
|
||||
body: ReqTalkReport;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* Talk Id
|
||||
*/
|
||||
talk_id: number;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/talk/{talk_id}/report';
|
||||
};
|
||||
|
||||
export type ReportTalkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type ReportTalkError = ReportTalkErrors[keyof ReportTalkErrors];
|
||||
|
||||
export type ReportTalkResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResWebPacketProtocol;
|
||||
};
|
||||
|
||||
export type ReportTalkResponse = ReportTalkResponses[keyof ReportTalkResponses];
|
||||
|
||||
export type BlockTalkAuthorData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* Talk Id
|
||||
*/
|
||||
talk_id: number;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/talk/{talk_id}/block';
|
||||
};
|
||||
|
||||
export type BlockTalkAuthorErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type BlockTalkAuthorError = BlockTalkAuthorErrors[keyof BlockTalkAuthorErrors];
|
||||
|
||||
export type BlockTalkAuthorResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResWebPacketProtocol;
|
||||
};
|
||||
|
||||
export type BlockTalkAuthorResponse = BlockTalkAuthorResponses[keyof BlockTalkAuthorResponses];
|
||||
|
||||
export type GetWatchSummaryData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
|
||||
@@ -28,6 +28,7 @@ import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateR
|
||||
import { MixSheet } from './myGak'
|
||||
import { useMyGak } from './myGakState'
|
||||
import { ownPage, useRegion } from './regionContext'
|
||||
import { TalkSheet } from './talk'
|
||||
import { useSky } from './skyContext'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
@@ -74,7 +75,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', talks: '동네 이야기' } as const
|
||||
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
@@ -135,6 +136,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{state.type === 'me' && <MeSheet onDone={onClose} />}
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
{state.type === 'mix' && <MixSheet ids={state.ids} shared={state.shared} onDone={onClose} />}
|
||||
{state.type === 'talks' && <TalkSheet />}
|
||||
</div>
|
||||
)}
|
||||
{!state && <RegionLinks />}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { PostCard, PostCardSkel } from './Post'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { TalkBand } from './talk'
|
||||
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { deg, slotAt } from './weatherText'
|
||||
|
||||
@@ -391,6 +392,7 @@ export function TodayPage() {
|
||||
<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" />}
|
||||
<TalkBand />
|
||||
<div>
|
||||
{load === 'loading' && <PostsSkel />}
|
||||
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
|
||||
|
||||
@@ -13,6 +13,7 @@ export type SheetState =
|
||||
| { type: 'me' }
|
||||
| { type: 'region' }
|
||||
| { type: 'mix'; ids?: number[]; shared?: boolean }
|
||||
| { type: 'talks' }
|
||||
| null
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import {
|
||||
addTalkMutation,
|
||||
blockTalkAuthorMutation,
|
||||
deleteTalkMutation,
|
||||
likeTalkMutation,
|
||||
listTalksInfiniteOptions,
|
||||
listTalksOptions,
|
||||
reportTalkMutation,
|
||||
unlikeTalkMutation,
|
||||
} from '../api/client/@tanstack/react-query.gen'
|
||||
import { TalkReport, type TalkData } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, kst, loadOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Avatar, Sec, StateBox, TAP44 } from './ui'
|
||||
|
||||
const BODY_MAX = 100
|
||||
const PREVIEW = 3
|
||||
|
||||
// 서버 ErrorType 이름 → 안내
|
||||
const WRITE_ERRORS: Record<string, string> = {
|
||||
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
|
||||
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
|
||||
INVALID_INPUT: '100자 안으로 써 주세요.',
|
||||
}
|
||||
|
||||
const REASONS = [
|
||||
[TalkReport.ABUSE, '욕설·비하'],
|
||||
[TalkReport.SPAM, '광고·도배'],
|
||||
[TalkReport.PRIVACY, '개인정보 노출'],
|
||||
[TalkReport.ETC, '기타'],
|
||||
] as const
|
||||
|
||||
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
|
||||
function slotWord(iso: string) {
|
||||
const h = kst(iso).h
|
||||
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤'
|
||||
}
|
||||
|
||||
function useRefreshTalks() {
|
||||
const queryClient = useQueryClient()
|
||||
return () => queryClient.invalidateQueries({ queryKey: [{ _id: 'listTalks' }] })
|
||||
}
|
||||
|
||||
function Composer() {
|
||||
const { region } = useRegion()
|
||||
const { loggedIn, me } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const refresh = useRefreshTalks()
|
||||
const add = useMutation(addTalkMutation())
|
||||
const [text, setText] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const body = text.trim()
|
||||
if (!body || add.isPending) return
|
||||
setError(null)
|
||||
add.mutate(
|
||||
{ body: { region_code: region.code, body } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
|
||||
setText('')
|
||||
refresh()
|
||||
},
|
||||
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="mx-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onFocus={() => !loggedIn && open({ type: 'login' })}
|
||||
readOnly={add.isPending}
|
||||
maxLength={BODY_MAX}
|
||||
rows={2}
|
||||
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
|
||||
aria-label="동네 이야기 쓰기"
|
||||
className="w-full resize-none rounded-2xl bg-[#f3f6fb] px-3 py-2.5 text-[14.5px]"
|
||||
/>
|
||||
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
|
||||
<span>{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
|
||||
<span className="ml-auto tabular-nums">
|
||||
{text.length}/{BODY_MAX}
|
||||
</span>
|
||||
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white disabled:opacity-40">
|
||||
{add.isPending ? '올리는 중…' : '올리기'}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="mt-1 mb-0 text-xs font-bold text-(--heart)" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function TalkRow({ t }: { t: TalkData }) {
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const refresh = useRefreshTalks()
|
||||
const [liked, setLiked] = useState(t.liked)
|
||||
const [count, setCount] = useState(t.like_count)
|
||||
const [menu, setMenu] = useState<'closed' | 'open' | 'report' | 'done'>('closed')
|
||||
const like = useMutation(likeTalkMutation())
|
||||
const unlike = useMutation(unlikeTalkMutation())
|
||||
const remove = useMutation(deleteTalkMutation())
|
||||
const report = useMutation(reportTalkMutation())
|
||||
const block = useMutation(blockTalkAuthorMutation())
|
||||
const [failed, setFailed] = useState(false)
|
||||
|
||||
const toggle = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (like.isPending || unlike.isPending) return
|
||||
const next = !liked
|
||||
setLiked(next)
|
||||
setCount((n) => n + (next ? 1 : -1))
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { talk_id: t.talk_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (res.result?.success && res.like_count != null) return setCount(res.like_count)
|
||||
setLiked(!next)
|
||||
setCount(t.like_count)
|
||||
},
|
||||
onError: () => {
|
||||
setLiked(!next)
|
||||
setCount(t.like_count)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
|
||||
const after = {
|
||||
onSuccess: (res: { result?: { success?: boolean } }) => {
|
||||
if (!res.result?.success) return setFailed(true)
|
||||
setMenu('done')
|
||||
refresh()
|
||||
},
|
||||
onError: () => setFailed(true),
|
||||
}
|
||||
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 border-b border-(--line) py-2.5 last:border-b-0">
|
||||
<Avatar character={t.character} color={t.color} mood={t.mood} />
|
||||
<div className="min-w-0">
|
||||
<small className="block text-xs font-bold text-(--ink3)">
|
||||
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
|
||||
{[t.region_name, slotWord(t.created_at), t.weather].filter(Boolean).join(' · ')}
|
||||
</small>
|
||||
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
|
||||
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
|
||||
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
|
||||
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
|
||||
{t.mine ? '내 글' : '더보기'}
|
||||
</button>
|
||||
</small>
|
||||
{menu !== 'closed' && (
|
||||
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
|
||||
{menu === 'done' ? (
|
||||
<span className="text-[#1f9d62]">처리했어요</span>
|
||||
) : t.mine ? (
|
||||
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, after)} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
|
||||
지우기
|
||||
</button>
|
||||
) : menu === 'report' ? (
|
||||
REASONS.map(([reason, label]) => (
|
||||
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after)} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
|
||||
{label}
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
|
||||
이 사람 글 안 보기
|
||||
</button>
|
||||
<button type="button" onClick={() => guard(() => setMenu('report'))} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
|
||||
신고하기
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{failed && (
|
||||
<span className="text-(--heart)" role="alert">
|
||||
못 했어요. 다시 해 주세요
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 오늘 탭의 동네 이야기: 쓰기 칸과 최근 글 몇 개 */
|
||||
export function TalkBand() {
|
||||
const { open } = useSheet()
|
||||
const q = useQuery(listTalksOptions())
|
||||
const talks = q.data?.talks ?? []
|
||||
const load = loadOf(q)
|
||||
return (
|
||||
<section aria-label="동네 이야기">
|
||||
<Sec title="동네 이야기" sub="전국 사람들이 쓰는 지금 날씨 이야기" />
|
||||
<Composer />
|
||||
<div className="relative mx-3 mt-2 min-h-[60px] rounded-[22px] bg-white px-3 py-1 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
{talks.length ? (
|
||||
talks.slice(0, PREVIEW).map((t) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />)
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => q.refetch()} empty="아직 글이 없어요. 첫 이야기를 남겨 보세요." className="inset-0" />
|
||||
)}
|
||||
{talks.length > PREVIEW && (
|
||||
<button type="button" onClick={() => open({ type: 'talks' })} className="w-full cursor-pointer border-t border-(--line) py-2.5 text-center text-sm font-bold text-(--ink2)">
|
||||
이야기 더 보기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 동네 이야기 전체 (아래로 더 받기) */
|
||||
export function TalkSheet() {
|
||||
const list = useInfiniteQuery({
|
||||
...listTalksInfiniteOptions(),
|
||||
initialPageParam: {},
|
||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||||
})
|
||||
const talks = list.data?.pages.flatMap((p) => p.talks ?? []) ?? []
|
||||
return (
|
||||
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-1.5 pb-[18px]">
|
||||
{talks.map((t) => (
|
||||
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
|
||||
))}
|
||||
{list.hasNextPage && (
|
||||
<button type="button" onClick={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 w-full cursor-pointer text-center text-sm font-bold text-(--ink3) disabled:opacity-50">
|
||||
{list.isFetchingNextPage ? '불러오는 중…' : '더 보기'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user