UNPKG

openapi-react-query

Version:

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

82 lines (78 loc) 2.52 kB
'use strict'; const reactQuery = require('@tanstack/react-query'); function createClient(client) { const queryFn = async ({ queryKey: [method, path, init], signal }) => { const mth = method.toUpperCase(); const fn = client[mth]; const { data, error, response } = await fn(path, { signal, ...init }); if (error) { throw error; } if (response.status === 204 || response.headers.get("Content-Length") === "0") { return data ?? null; } return data; }; const queryOptions = (method, path, ...[init, options]) => ({ queryKey: init === void 0 ? [method, path] : [method, path, init], queryFn, ...options }); return { queryOptions, useQuery: (method, path, ...[init, options, queryClient]) => reactQuery.useQuery(queryOptions(method, path, init, options), queryClient), useSuspenseQuery: (method, path, ...[init, options, queryClient]) => reactQuery.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 reactQuery.useInfiniteQuery( { queryKey, queryFn: async ({ queryKey: [method2, path2, init2], pageParam = 0, signal }) => { const mth = method2.toUpperCase(); const fn = client[mth]; const mergedInit = { ...init2, signal, params: { ...init2?.params || {}, query: { ...init2?.params?.query, [pageParamName]: pageParam } } }; const { data, error } = await fn(path2, mergedInit); if (error) { throw error; } return data; }, ...restOptions }, queryClient ); }, useMutation: (method, path, options, queryClient) => reactQuery.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 ) }; } module.exports = createClient; //# sourceMappingURL=index.cjs.map