Coves frontend - a photon fork
1// ---------------------------------------------------------------------------
2// Sort and listing type validation
3// ---------------------------------------------------------------------------
4
5export type CovesSortType = 'hot' | 'new' | 'top'
6export type CovesTimeframe = 'day' | 'week' | 'month' | 'all'
7export type CovesListingType = 'discover' | 'timeline'
8
9export type CovesSortParams =
10 | { sort: 'hot'; timeframe?: undefined }
11 | { sort: 'new'; timeframe?: undefined }
12 | { sort: 'top'; timeframe: CovesTimeframe }
13
14const VALID_SORTS: ReadonlySet<CovesSortType> = new Set<CovesSortType>([
15 'hot',
16 'new',
17 'top',
18])
19const VALID_TIMEFRAMES: ReadonlySet<CovesTimeframe> = new Set<CovesTimeframe>([
20 'day',
21 'week',
22 'month',
23 'all',
24])
25
26function isValidSort(s: string): s is CovesSortType {
27 return (VALID_SORTS as ReadonlySet<string>).has(s)
28}
29
30function isValidTimeframe(t: string): t is CovesTimeframe {
31 return (VALID_TIMEFRAMES as ReadonlySet<string>).has(t)
32}
33
34/**
35 * Validates and returns Coves API sort + timeframe parameters.
36 * Falls back to `{ sort: 'hot' }` for invalid input.
37 */
38export function mapSort(sort: string, timeframe?: string): CovesSortParams {
39 if (!isValidSort(sort)) {
40 console.warn(`[sort] Invalid sort value "${sort}", falling back to "hot"`)
41 return { sort: 'hot' }
42 }
43 if (sort === 'top') {
44 if (timeframe && isValidTimeframe(timeframe)) {
45 return { sort: 'top', timeframe }
46 }
47 if (timeframe) {
48 console.warn(
49 `[sort] Invalid timeframe "${timeframe}", falling back to "all"`,
50 )
51 }
52 return { sort: 'top', timeframe: 'all' }
53 }
54 return { sort }
55}
56
57/**
58 * Validates and returns Coves listing type.
59 * Falls back to `'discover'` for invalid input or unauthenticated timeline requests.
60 */
61export function mapListing(
62 listing: string,
63 isAuthenticated: boolean,
64): CovesListingType {
65 if (listing === 'timeline') return isAuthenticated ? 'timeline' : 'discover'
66 if (listing !== 'discover') {
67 console.warn(
68 `[sort] Invalid listing type "${listing}", falling back to "discover"`,
69 )
70 }
71 return 'discover'
72}