import { parseAsInteger, parseAsString, parseAsStringLiteral } from 'nuqs'; import type { Post } from '@/entities/post'; const SORT_ORDERS = ['asc', 'desc'] as const; export type SortOrder = (typeof SORT_ORDERS)[number]; export const PAGE_SIZE = 5; export const postSearchParsers = { keyword: parseAsString.withDefault(''), author: parseAsInteger, sort: parseAsStringLiteral(SORT_ORDERS), page: parseAsInteger.withDefault(1), }; export const filterByAuthor = (posts: Post[], author: number | null) => author === null ? posts : posts.filter((post) => post.userId === author); export const toSortingState = (sort: SortOrder | null) => sort === null ? [] : [{ id: 'title', desc: sort === 'desc' }]; export const toNextSort = (sort: SortOrder | null) => { // oxlint-disable-next-line unicorn/no-null -- nuqs는 URL 파라미터 제거를 null로 표현한다 const NEXT_SORT = { asc: 'desc', desc: null } as const; return sort === null ? 'asc' : NEXT_SORT[sort]; }; export const toAuthorIds = (posts: Post[]) => [...new Set(posts.map((post) => post.userId))].sort((a, b) => a - b); export const toAvgBodyLength = (posts: Post[]) => posts.length === 0 ? 0 : Math.round( posts.reduce((sum, post) => sum + post.body.length, 0) / posts.length ); export const toEmptyMessage = (filteredCount: number) => filteredCount === 0 ? '검색 결과가 없어요.' : '이 페이지에는 글이 없어요. 이전 페이지로 가 보세요.';