Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 37 additions & 26 deletions app/api/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@
* Copyright Oxide Computer Company
*/
import {
hashKey,
queryOptions,
useMutation,
useQueries,
useQuery,
type DefaultError,
type FetchQueryOptions,
type InvalidateQueryFilters,
type QueryClient,
type QueryKey,
type UndefinedInitialDataOptions,
type UseMutationOptions,
type UseQueryOptions,
type UseQueryResult,
} from '@tanstack/react-query'
import { type SetNonNullable } from 'type-fest'

Expand Down Expand Up @@ -100,14 +104,14 @@ type FetchQueryOtherOptions<T, E = DefaultError> = Omit<
'queryKey' | 'queryFn'
>

export const getUseApiQuery =
export const getApiQueryOptions =
<A extends ApiClient>(api: A) =>
<M extends string & keyof A>(
method: M,
params: Params<A[M]>,
options: UseQueryOtherOptions<Result<A[M]>, ApiError> = {}
) => {
return useQuery({
) =>
queryOptions({
queryKey: [method, params],
// no catch, let unexpected errors bubble up
queryFn: ({ signal }) => api[method](params, { signal }).then(handleResult(method)),
Expand All @@ -118,7 +122,15 @@ export const getUseApiQuery =
throwOnError: (err) => err.statusCode === 404,
...options,
})
}

export const getUseApiQuery =
<A extends ApiClient>(api: A) =>
<M extends string & keyof A>(
method: M,
params: Params<A[M]>,
options: UseQueryOtherOptions<Result<A[M]>, ApiError> = {}
) =>
useQuery(getApiQueryOptions(api)(method, params, options))

export const getUsePrefetchedApiQuery =
<A extends ApiClient>(api: A) =>
Expand All @@ -127,33 +139,32 @@ export const getUsePrefetchedApiQuery =
params: Params<A[M]>,
options: UseQueryOtherOptions<Result<A[M]>, ApiError> = {}
) => {
const queryKey = [method, params]
const result = useQuery({
queryKey,
// no catch, let unexpected errors bubble up
queryFn: ({ signal }) => api[method](params, { signal }).then(handleResult(method)),
const qOptions = getApiQueryOptions(api)(method, params, options)
return ensure(useQuery(qOptions), qOptions.queryKey)
}

// we can say Not Found. If you need to allow a 404 and want it to show
// up as `error` state instead, pass `useErrorBoundary: false` as an
// option from the calling component and it will override this
throwOnError: (err) => err.statusCode === 404,
...options,
})
invariant(
result.data,
`Expected query to be prefetched.
Key: ${JSON.stringify(queryKey)}
const prefetchError = (key?: QueryKey) =>
`Expected query to be prefetched.
Key: ${key ? hashKey(key) : '<unknown>'}
Ensure the following:
• loader is called in routes.tsx and is running
• query matches in both the loader and the component
• request isn't erroring-out server-side (check the Networking tab)
• mock API endpoint is implemented in handlers.ts
`
)
// TS infers non-nullable on a freestanding variable, but doesn't like to do
// it on a property. So we give it a hint
return result as SetNonNullable<typeof result, 'data'>
}
• mock API endpoint is implemented in handlers.ts`

export function ensure<TData, TError>(
result: UseQueryResult<TData, TError>,
/**
* Optional because if we call this manually from a component like
* `ensure(useQuery(...))`, * we don't necessarily have access to the key.
*/
key?: QueryKey
) {
invariant(result.data, prefetchError(key))
// TS infers non-nullable on a freestanding variable, but doesn't like to do
// it on a property. So we give it a hint
return result as SetNonNullable<typeof result, 'data'>
}

const ERRORS_ALLOWED = 'errors-allowed'

Expand Down
6 changes: 5 additions & 1 deletion test/e2e/breadcrumbs.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ test('breadcrumbs', async ({ page }) => {
// the form route doesn't have its own crumb
await page.getByRole('link', { name: 'New VPC' }).click()
await expect(page).toHaveURL('/projects/mock-project/vpcs-new')
await expect(page.getByRole('dialog', { name: 'Create VPC' })).toBeVisible()
await expectCrumbs(page, vpcsCrumbs)

// try a nested one with a tab
await page.goto('/projects/mock-project/instances/db1/networking')
await expect(page.getByRole('tab', { name: 'Networking' })).toBeVisible()
await expectCrumbs(page, [
...projectCrumbs,
['Instances', '/projects/mock-project/instances'],
Expand Down Expand Up @@ -77,6 +79,8 @@ test('breadcrumbs', async ({ page }) => {
['ip-pool-1', '/system/networking/ip-pools/ip-pool-1'],
]
await expectCrumbs(page, poolCrumbs)
await page.goto('/system/networking/ip-pools/ip-pool-1/ranges-add')
await page.getByRole('link', { name: 'Add range' }).click()
await expect(page).toHaveURL('/system/networking/ip-pools/ip-pool-1/ranges-add')
await expect(page.getByRole('dialog', { name: 'Add IP range' })).toBeVisible()
await expectCrumbs(page, poolCrumbs)
})