Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

api.ts

53 lines1.2 KB

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()
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
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 },