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

api.ts

63 lines1.5 KB

1import { queryOptions } from '@tanstack/lit-query'
2​
3export const DATA_QUERY_KEY = ['ssr-example-data'] as const
4export const DEFAULT_MESSAGE = 'Hello from SSR!'
5export const QUERY_STALE_TIME = 30000
6​
7export type DataResponse = {
8 message: string
9 requestCount: number
10 servedAt: string
12​
13function resolveApiUrl(pathname: string, apiBaseUrl: string): string {
14 if (!apiBaseUrl) {
15 return pathname
16 }
17​
18 return new URL(pathname, apiBaseUrl).toString()
20​
21async function readJson<TResponse>(response: Response): Promise<TResponse> {
22 let payload: TResponse | { error?: string } | null = null
23​
24 try {
25 payload = (await response.json()) as TResponse | { error?: string }
26 } catch {
27 if (response.ok) {
28 throw new Error(
29 `Failed to parse JSON response with status ${response.status}.`,
30 )
31 }
32 }
33​
34 if (!response.ok) {
35 const errorDetail =
36 payload &&
37 typeof payload === 'object' &&
38 'error' in payload &&
39 typeof payload.error === 'string'
40 ? `: ${payload.error}`
41 : ''
42​
43 throw new Error(
44 `Request failed with status ${response.status}${errorDetail}`,
45 )
46 }
47​
48 return payload as TResponse
50​
51export function createDataQueryOptions(apiBaseUrl = '') {
52 return queryOptions({
53 queryKey: [...DATA_QUERY_KEY, apiBaseUrl] as const,
54 queryFn: async ({ signal }) => {
55 const response = await fetch(resolveApiUrl('/api/data', apiBaseUrl), {
56 signal,
57 })
58 return readJson<DataResponse>(response)
59 },
60 retry: false,
61 staleTime: QUERY_STALE_TIME,
62 })