export const getChapters = async ({ token }: { token: string }): Promise => { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/chapters`, { headers: { Authorization: `Bearer ${token}` } }); const chapters = (await res.json()) as Chapter[]; if (!res.ok) { throw new Error('Failed to fetch puzzles'); } if (!chapters) { return []; } return chapters; }; export const getChapter = async ({ token, id }: { token: string; id: number; }): Promise => { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/chapter/${id}`, { headers: { Authorization: `Bearer ${token}` } }); const chapter = (await res.json()) as Chapter; if (!res.ok) { throw new Error('Failed to fetch puzzles'); } if (!chapter) { return null; } return chapter; }; export const getPuzzles = async ({ token }: { token: string }): Promise => { const chapters = await getChapters({ token }); if (!chapters) { return []; } for (let i = 0; i < chapters.length; i++) { let chapter = chapters[i]; chapter = (await getChapter({ token, id: chapter.id })) as Chapter; if (!chapter) continue; chapters[i].puzzles = chapter.puzzles; } return chapters; }; export const getPuzzle = async ({ token, id }: { token: string; id: number; }): Promise => { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/puzzle/${id}`, { headers: { Authorization: `Bearer ${token}` } }); const puzzle = (await res.json()) as Puzzle; if (!res.ok) { throw new Error('Failed to fetch puzzle'); } if (!puzzle) { return null; } return puzzle; }; export type Puzzle = { id: number; name: string; content: string; scoreMax: number; tags: Tag[] | null; tries?: number; score?: number; }; export type Chapter = { id: number; name: string; puzzles: Puzzle[]; startDate?: string; endDate?: string; }; export type Tag = { name: string; };