UNPKG

openapi-react-query

Version:

Fast, type-safe @tanstack/react-query client to work with your OpenAPI schema.

64 lines 2.68 kB
import { useMutation, useQuery, useSuspenseQuery, useInfiniteQuery, } from "@tanstack/react-query"; export default function createClient(client) { const queryFn = async ({ queryKey: [method, path, init], signal, }) => { const mth = method.toUpperCase(); const fn = client[mth]; const { data, error } = await fn(path, { signal, ...init }); if (error) { throw error; } return data; }; const queryOptions = (method, path, ...[init, options]) => ({ queryKey: (init === undefined ? [method, path] : [method, path, init]), queryFn, ...options, }); return { queryOptions, useQuery: (method, path, ...[init, options, queryClient]) => useQuery(queryOptions(method, path, init, options), queryClient), useSuspenseQuery: (method, path, ...[init, options, queryClient]) => useSuspenseQuery(queryOptions(method, path, init, options), queryClient), useInfiniteQuery: (method, path, init, options, queryClient) => { const { pageParamName = "cursor", ...restOptions } = options; const { queryKey } = queryOptions(method, path, init); return useInfiniteQuery({ queryKey, queryFn: async ({ queryKey: [method, path, init], pageParam = 0, signal }) => { const mth = method.toUpperCase(); const fn = client[mth]; const mergedInit = { ...init, signal, params: { ...(init?.params || {}), query: { ...init?.params?.query, [pageParamName]: pageParam, }, }, }; const { data, error } = await fn(path, mergedInit); if (error) { throw error; } return data; }, ...restOptions, }, queryClient); }, useMutation: (method, path, options, queryClient) => useMutation({ mutationKey: [method, path], mutationFn: async (init) => { const mth = method.toUpperCase(); const fn = client[mth]; const { data, error } = await fn(path, init); if (error) { throw error; } return data; }, ...options, }, queryClient), }; } //# sourceMappingURL=index.js.map