|
| 1 | +/* |
| 2 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 3 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 4 | + * file, you can obtain one at https://mozilla.org/MPL/2.0/. |
| 5 | + * |
| 6 | + * Copyright Oxide Computer Company |
| 7 | + */ |
| 8 | +import { QueryClient } from '@tanstack/react-query' |
| 9 | + |
| 10 | +import { Api } from './__generated__/Api' |
| 11 | +import { |
| 12 | + getUseApiMutation, |
| 13 | + getUseApiQueries, |
| 14 | + getUseApiQuery, |
| 15 | + getUseApiQueryClient, |
| 16 | + getUseApiQueryErrorsAllowed, |
| 17 | + getUsePrefetchedApiQuery, |
| 18 | + wrapQueryClient, |
| 19 | +} from './hooks' |
| 20 | + |
| 21 | +export const api = new Api({ |
| 22 | + // unit tests run in Node, whose fetch implementation requires a full URL |
| 23 | + host: process.env.NODE_ENV === 'test' ? 'http://testhost' : '', |
| 24 | +}) |
| 25 | + |
| 26 | +// add the API client to window for use from the browser JS console. requests |
| 27 | +// will use the session cookie, same as normal API calls |
| 28 | +if (typeof window !== 'undefined') { |
| 29 | + // @ts-expect-error |
| 30 | + window.oxide = api.methods |
| 31 | +} |
| 32 | + |
| 33 | +export type ApiMethods = typeof api.methods |
| 34 | + |
| 35 | +export const useApiQuery = getUseApiQuery(api.methods) |
| 36 | +export const useApiQueries = getUseApiQueries(api.methods) |
| 37 | +/** |
| 38 | + * Same as `useApiQuery`, except we use `invariant(data)` to ensure the data is |
| 39 | + * already there in the cache at request time, which means it has been |
| 40 | + * prefetched in a loader. Whenever this hook is used, there should be an e2e |
| 41 | + * test loading the page to exercise the invariant in CI. |
| 42 | + */ |
| 43 | +export const usePrefetchedApiQuery = getUsePrefetchedApiQuery(api.methods) |
| 44 | +export const useApiQueryErrorsAllowed = getUseApiQueryErrorsAllowed(api.methods) |
| 45 | +export const useApiMutation = getUseApiMutation(api.methods) |
| 46 | + |
| 47 | +// Needs to be defined here instead of in app so we can use it to define |
| 48 | +// `apiQueryClient`, which provides API-typed versions of QueryClient methods |
| 49 | +export const queryClient = new QueryClient({ |
| 50 | + defaultOptions: { |
| 51 | + queries: { |
| 52 | + retry: false, |
| 53 | + staleTime: 10000, |
| 54 | + refetchOnWindowFocus: false, |
| 55 | + }, |
| 56 | + }, |
| 57 | +}) |
| 58 | + |
| 59 | +// to be used in loaders, which are outside the component tree and therefore |
| 60 | +// don't have access to context |
| 61 | +export const apiQueryClient = wrapQueryClient(api.methods, queryClient) |
| 62 | + |
| 63 | +// to be used to retrieve the typed query client in components |
| 64 | +export const useApiQueryClient = getUseApiQueryClient(api.methods) |
0 commit comments