Open History to see the last commit
1import type { DataResponse } from './types.js'
2β
3export const DEFAULT_MESSAGE = 'Hello from SSR!'
4β
5function resolveApiUrl(pathname: string, apiBaseUrl: string): string {
6 if (!apiBaseUrl) {
7 return pathname
8 }
9β
10 return new URL(pathname, apiBaseUrl).toString()
11}
12β
13async function readJson<TResponse>(response: Response): Promise<TResponse> {
14 let payload: TResponse | { error?: string } | null = null
15β
16 try {
17 payload = (await response.json()) as TResponse | { error?: string }
18 } catch {
19 if (response.ok) {
20 throw new Error(
21 `Failed to parse JSON response with status ${response.status}.`,
22 )
23 }
24 }
25β
26 if (!response.ok) {
27 const errorDetail =
28 payload &&
29 typeof payload === 'object' &&
30 'error' in payload &&
31 typeof payload.error === 'string'
32 ? `: ${payload.error}`
33 : ''
34β
35 throw new Error(
36 `Request failed with status ${response.status}${errorDetail}`,
37 )
38 }
39β
40 return payload as TResponse
41}
42β
43export const dataAPI = {
44 getData: async (
45 apiBaseUrl: string,
46 signal: AbortSignal,
47 ): Promise<DataResponse> => {
48 const response = await fetch(resolveApiUrl('/api/data', apiBaseUrl), {
49 signal,
50 })
51 return readJson<DataResponse>(response)
52 },
53}