@geekmidas/client 10.0.0-alpha.11 → 10.0.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-fetcher.cjs +76 -3
- package/dist/auth-fetcher.cjs.map +1 -0
- package/dist/auth-fetcher.d.cts +155 -3
- package/dist/auth-fetcher.d.cts.map +1 -0
- package/dist/auth-fetcher.d.mts +155 -3
- package/dist/auth-fetcher.d.mts.map +1 -0
- package/dist/auth-fetcher.mjs +75 -3
- package/dist/auth-fetcher.mjs.map +1 -0
- package/dist/endpoint-hooks.cjs +11 -15
- package/dist/endpoint-hooks.cjs.map +1 -1
- package/dist/endpoint-hooks.d.cts +4 -7
- package/dist/endpoint-hooks.d.cts.map +1 -1
- package/dist/endpoint-hooks.d.mts +4 -7
- package/dist/endpoint-hooks.d.mts.map +1 -1
- package/dist/endpoint-hooks.mjs +5 -9
- package/dist/endpoint-hooks.mjs.map +1 -1
- package/dist/fetcher.cjs +110 -3
- package/dist/fetcher.cjs.map +1 -0
- package/dist/fetcher.d.cts +22 -3
- package/dist/fetcher.d.cts.map +1 -0
- package/dist/fetcher.d.mts +22 -3
- package/dist/fetcher.d.mts.map +1 -0
- package/dist/fetcher.mjs +85 -2
- package/dist/fetcher.mjs.map +1 -0
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -6
- package/dist/infer.cjs +0 -1
- package/dist/infer.d.cts +130 -2
- package/dist/infer.d.cts.map +1 -0
- package/dist/infer.d.mts +130 -2
- package/dist/infer.d.mts.map +1 -0
- package/dist/infer.mjs +1 -1
- package/dist/openapi-hooks.cjs +13 -16
- package/dist/openapi-hooks.cjs.map +1 -1
- package/dist/openapi-hooks.d.cts +8 -11
- package/dist/openapi-hooks.d.cts.map +1 -1
- package/dist/openapi-hooks.d.mts +8 -11
- package/dist/openapi-hooks.d.mts.map +1 -1
- package/dist/openapi-hooks.mjs +9 -12
- package/dist/openapi-hooks.mjs.map +1 -1
- package/dist/openapi-types.d.cts +2 -4
- package/dist/openapi-types.d.cts.map +1 -1
- package/dist/openapi-types.d.mts +2 -4
- package/dist/openapi-types.d.mts.map +1 -1
- package/dist/openapi.cjs +25 -23
- package/dist/openapi.cjs.map +1 -1
- package/dist/openapi.d.cts +494 -0
- package/dist/openapi.d.cts.map +1 -0
- package/dist/openapi.d.mts +494 -0
- package/dist/openapi.d.mts.map +1 -0
- package/dist/openapi.mjs +1 -1
- package/dist/openapi.mjs.map +1 -1
- package/dist/react-query.cjs +17 -16
- package/dist/react-query.cjs.map +1 -1
- package/dist/react-query.d.cts +12 -17
- package/dist/react-query.d.cts.map +1 -1
- package/dist/react-query.d.mts +12 -17
- package/dist/react-query.d.mts.map +1 -1
- package/dist/react-query.mjs +10 -9
- package/dist/react-query.mjs.map +1 -1
- package/dist/types.cjs +0 -1
- package/dist/types.d.cts +109 -2
- package/dist/types.d.cts.map +1 -0
- package/dist/types.d.mts +109 -2
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +1 -1
- package/package.json +5 -5
- package/dist/auth-fetcher-CBYuL6rx.d.cts +0 -158
- package/dist/auth-fetcher-CBYuL6rx.d.cts.map +0 -1
- package/dist/auth-fetcher-DOj0iz21.mjs +0 -77
- package/dist/auth-fetcher-DOj0iz21.mjs.map +0 -1
- package/dist/auth-fetcher-DxS8zOLc.d.mts +0 -158
- package/dist/auth-fetcher-DxS8zOLc.d.mts.map +0 -1
- package/dist/auth-fetcher-HILABmws.cjs +0 -82
- package/dist/auth-fetcher-HILABmws.cjs.map +0 -1
- package/dist/chunk-CUT6urMc.cjs +0 -30
- package/dist/fetcher-C1xtCKpT.d.mts +0 -25
- package/dist/fetcher-C1xtCKpT.d.mts.map +0 -1
- package/dist/fetcher-CakjC9C7.mjs +0 -88
- package/dist/fetcher-CakjC9C7.mjs.map +0 -1
- package/dist/fetcher-CwnSqc4D.cjs +0 -100
- package/dist/fetcher-CwnSqc4D.cjs.map +0 -1
- package/dist/fetcher-cDrfwN-Y.d.cts +0 -25
- package/dist/fetcher-cDrfwN-Y.d.cts.map +0 -1
- package/dist/infer-6KKCgmg1.cjs +0 -0
- package/dist/infer-CPRqfabW.d.cts +0 -133
- package/dist/infer-CPRqfabW.d.cts.map +0 -1
- package/dist/infer-D9CgpOuc.d.mts +0 -133
- package/dist/infer-D9CgpOuc.d.mts.map +0 -1
- package/dist/infer-uCUq1whM.mjs +0 -0
- package/dist/types-BH8WgGrm.mjs +0 -0
- package/dist/types-BMGM6sZc.d.mts +0 -110
- package/dist/types-BMGM6sZc.d.mts.map +0 -1
- package/dist/types-DMQMHePI.d.cts +0 -110
- package/dist/types-DMQMHePI.d.cts.map +0 -1
- package/dist/types-a8gm_IaQ.cjs +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-hooks.cjs","names":["endpoint: T","config?: FilteredRequestConfig<Paths, T>","key: unknown[]","fetcher: TypedApiFunction<Paths>","options: CreateEndpointHooksOptions","mutationOptions?: Omit<\n\t\t\t\tUseMutationOptions<\n\t\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\t\tError,\n\t\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t\t>,\n\t\t\t\t'mutationFn'\n\t\t\t>","config: FilteredRequestConfig<Paths, T>","options: Omit<\n\t\t\t\tUseInfiniteQueryOptions<\n\t\t\t\t\tTPageData,\n\t\t\t\t\tError,\n\t\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\t\tunknown[],\n\t\t\t\t\tTPageParam\n\t\t\t\t>,\n\t\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t\t> & {\n\t\t\t\tgetNextPageParam: (\n\t\t\t\t\tlastPage: TPageData,\n\t\t\t\t\tallPages: TPageData[],\n\t\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\t\tallPageParams: TPageParam[],\n\t\t\t\t) => TPageParam | undefined;\n\t\t\t\tinitialPageParam: TPageParam;\n\t\t\t}","options"],"sources":["../src/endpoint-hooks.ts"],"sourcesContent":["import type {\n\tQueryClient,\n\tQueryFunctionContext,\n\tUseInfiniteQueryOptions,\n\tUseInfiniteQueryResult,\n\tUseMutationOptions,\n\tUseMutationResult,\n\tUseQueryOptions,\n\tUseQueryResult,\n} from '@tanstack/react-query';\nimport { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport type {\n\tExtractEndpointResponse,\n\tFilteredRequestConfig,\n\tIsConfigRequired,\n\tMutationEndpoint,\n\tQueryEndpoint,\n\tTypedApiFunction,\n} from './types';\n\n/**\n * Build query key from endpoint and config\n */\nfunction buildQueryKey<Paths, T extends QueryEndpoint<Paths>>(\n\tendpoint: T,\n\tconfig?: FilteredRequestConfig<Paths, T>,\n): unknown[] {\n\tconst key: unknown[] = [endpoint];\n\n\tif (config && 'params' in config && config.params) {\n\t\tkey.push({ params: config.params });\n\t}\n\n\tif (config && 'query' in config && config.query) {\n\t\tkey.push({ query: config.query });\n\t}\n\n\treturn key;\n}\n\n/**\n * Options for creating endpoint-based hooks\n */\nexport interface CreateEndpointHooksOptions {\n\tqueryClient?: QueryClient;\n}\n\n/**\n * Hook options type that conditionally requires config\n */\ntype UseQueryArgs<Paths, T extends QueryEndpoint<Paths>> = IsConfigRequired<\n\tPaths,\n\tT\n> extends true\n\t? [\n\t\t\tconfig: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t]\n\t: [\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t];\n\n/**\n * Endpoint-based React Query hooks\n */\nexport interface EndpointHooks<Paths> {\n\t/**\n\t * Use query hook for GET endpoints.\n\t * Config is required when endpoint has path params.\n\t */\n\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\t...args: UseQueryArgs<Paths, T>\n\t) => UseQueryResult<ExtractEndpointResponse<Paths, T>, Error>;\n\n\t/**\n\t * Use mutation hook for POST, PUT, PATCH, DELETE endpoints.\n\t * Config with params/body is passed to mutate().\n\t */\n\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\toptions?: Omit<\n\t\t\tUseMutationOptions<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>,\n\t\t\t'mutationFn'\n\t\t>,\n\t) => UseMutationResult<\n\t\tExtractEndpointResponse<Paths, T>,\n\t\tError,\n\t\tFilteredRequestConfig<Paths, T>\n\t>;\n\n\t/**\n\t * Use infinite query hook for paginated GET endpoints.\n\t */\n\tuseInfiniteQuery: <\n\t\tT extends QueryEndpoint<Paths>,\n\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\tTPageParam = unknown,\n\t>(\n\t\tendpoint: T,\n\t\toptions: Omit<\n\t\t\tUseInfiniteQueryOptions<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>,\n\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t> & {\n\t\t\tgetNextPageParam: (\n\t\t\t\tlastPage: TPageData,\n\t\t\t\tallPages: TPageData[],\n\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\tallPageParams: TPageParam[],\n\t\t\t) => TPageParam | undefined;\n\t\t\tinitialPageParam: TPageParam;\n\t\t},\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => UseInfiniteQueryResult<\n\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\tError\n\t>;\n\n\t/**\n\t * Invalidate queries for a specific endpoint.\n\t */\n\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => Promise<void>;\n\n\t/**\n\t * Invalidate all queries in the cache.\n\t */\n\tinvalidateAllQueries: () => Promise<void>;\n\n\t/**\n\t * Build a query key for manual cache operations\n\t */\n\tbuildQueryKey: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => unknown[];\n}\n\n/**\n * Create endpoint-based React Query hooks from a typed fetcher.\n *\n * @example\n * ```typescript\n * const fetcher = createAuthAwareFetcher<paths>({ ... });\n * const hooks = createEndpointHooks<paths>(fetcher);\n *\n * // In a component\n * const { data } = hooks.useQuery('GET /users/{id}', { params: { id: '123' } });\n *\n * const mutation = hooks.useMutation('POST /users');\n * await mutation.mutateAsync({ body: { name: 'John' } });\n * ```\n */\nexport function createEndpointHooks<Paths>(\n\tfetcher: TypedApiFunction<Paths>,\n\toptions: CreateEndpointHooksOptions = {},\n): EndpointHooks<Paths> {\n\treturn {\n\t\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\t...args: UseQueryArgs<Paths, T>\n\t\t) => {\n\t\t\t// Parse args - config is first, options is second\n\t\t\tconst [config, queryOptions] = args as [\n\t\t\t\tFilteredRequestConfig<Paths, T> | undefined,\n\t\t\t\t(\n\t\t\t\t\t| Omit<\n\t\t\t\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t\t\t >\n\t\t\t\t\t| undefined\n\t\t\t\t),\n\t\t\t];\n\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: () =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...queryOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, queryOptions],\n\t\t\t);\n\n\t\t\treturn useQuery<ExtractEndpointResponse<Paths, T>, Error>(\n\t\t\t\tmemoizedOptions,\n\t\t\t);\n\t\t},\n\n\t\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tmutationOptions?: Omit<\n\t\t\t\tUseMutationOptions<\n\t\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\t\tError,\n\t\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t\t>,\n\t\t\t\t'mutationFn'\n\t\t\t>,\n\t\t) => {\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tmutationFn: (config: FilteredRequestConfig<Paths, T>) =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...mutationOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, fetcher, mutationOptions],\n\t\t\t);\n\n\t\t\treturn useMutation<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tuseInfiniteQuery: <\n\t\t\tT extends QueryEndpoint<Paths>,\n\t\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\t\tTPageParam = unknown,\n\t\t>(\n\t\t\tendpoint: T,\n\t\t\toptions: Omit<\n\t\t\t\tUseInfiniteQueryOptions<\n\t\t\t\t\tTPageData,\n\t\t\t\t\tError,\n\t\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\t\tunknown[],\n\t\t\t\t\tTPageParam\n\t\t\t\t>,\n\t\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t\t> & {\n\t\t\t\tgetNextPageParam: (\n\t\t\t\t\tlastPage: TPageData,\n\t\t\t\t\tallPages: TPageData[],\n\t\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\t\tallPageParams: TPageParam[],\n\t\t\t\t) => TPageParam | undefined;\n\t\t\t\tinitialPageParam: TPageParam;\n\t\t\t},\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: ({\n\t\t\t\t\t\tpageParam,\n\t\t\t\t\t}: QueryFunctionContext<unknown[], TPageParam>) => {\n\t\t\t\t\t\tlet mergedConfig = config;\n\t\t\t\t\t\tif (pageParam !== undefined && config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = {\n\t\t\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\t\tquery: { ...(config as any).query, ...pageQuery },\n\t\t\t\t\t\t\t} as any;\n\t\t\t\t\t\t} else if (pageParam !== undefined && !config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = { query: pageQuery } as any;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, mergedConfig) as Promise<TPageData>;\n\t\t\t\t\t},\n\t\t\t\t\t...options,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, options],\n\t\t\t);\n\n\t\t\treturn useInfiniteQuery<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\t\t\treturn options.queryClient.invalidateQueries({\n\t\t\t\tqueryKey,\n\t\t\t\texact: !!config,\n\t\t\t});\n\t\t},\n\n\t\tinvalidateAllQueries: () => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateAllQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn options.queryClient.invalidateQueries();\n\t\t},\n\n\t\tbuildQueryKey,\n\t};\n}\n"],"mappings":";;;;;;;;AAwBA,SAAS,cACRA,UACAC,QACY;CACZ,MAAMC,MAAiB,CAAC,QAAS;AAEjC,KAAI,UAAU,YAAY,UAAU,OAAO,OAC1C,KAAI,KAAK,EAAE,QAAQ,OAAO,OAAQ,EAAC;AAGpC,KAAI,UAAU,WAAW,UAAU,OAAO,MACzC,KAAI,KAAK,EAAE,OAAO,OAAO,MAAO,EAAC;AAGlC,QAAO;AACP;;;;;;;;;;;;;;;;AAsID,SAAgB,oBACfC,SACAC,UAAsC,CAAE,GACjB;AACvB,QAAO;EACN,UAAU,CACTJ,UACA,GAAG,SACC;GAEJ,MAAM,CAAC,QAAQ,aAAa,GAAG;GAW/B,MAAM,WAAW,cAAc,UAAU,OAAO;GAEhD,MAAM,kBAAkB,mBACvB,OAAO;IACN;IACA,SAAS,MAER,AACC,QAIC,UAAU,OAAO;IACpB,GAAG;GACH,IACD;IAAC;IAAU;IAAQ;IAAS;IAAU;GAAa,EACnD;AAED,UAAO,qCACN,gBACA;EACD;EAED,aAAa,CACZA,UACAK,oBAQI;GACJ,MAAM,kBAAkB,mBACvB,OAAO;IACN,YAAY,CAACC,WAEZ,AACC,QAIC,UAAU,OAAO;IACpB,GAAG;GACH,IACD;IAAC;IAAU;IAAS;GAAgB,EACpC;AAED,UAAO,wCAIL,gBAAgB;EAClB;EAED,kBAAkB,CAKjBN,UACAO,WAkBAN,WACI;GACJ,MAAM,WAAW,cAAc,UAAU,OAAO;GAEhD,MAAM,kBAAkB,mBACvB,OAAO;IACN;IACA,SAAS,CAAC,EACT,WAC6C,KAAK;KAClD,IAAI,eAAe;AACnB,SAAI,wBAA2B,QAAQ;MACtC,MAAM,mBACE,cAAc,WAAW,YAAY,EAAE,MAAM,UAAW;AAChE,qBAAe;OACd,GAAG;OACH,OAAO;QAAE,GAAI,OAAe;QAAO,GAAG;OAAW;MACjD;KACD,WAAU,yBAA4B,QAAQ;MAC9C,MAAM,mBACE,cAAc,WAAW,YAAY,EAAE,MAAM,UAAW;AAChE,qBAAe,EAAE,OAAO,UAAW;KACnC;AACD,YAAO,AACN,QAIC,UAAU,aAAa;IACzB;IACD,GAAGO;GACH,IACD;IAAC;IAAU;IAAQ;IAAS;IAAUA;GAAQ,EAC9C;AAED,UAAO,6CAML,gBAAgB;EAClB;EAED,mBAAmB,CAClBR,UACAC,WACI;AACJ,QAAK,QAAQ,YACZ,OAAM,IAAI,MACT;GAGF,MAAM,WAAW,cAAc,UAAU,OAAO;AAChD,UAAO,QAAQ,YAAY,kBAAkB;IAC5C;IACA,SAAS;GACT,EAAC;EACF;EAED,sBAAsB,MAAM;AAC3B,QAAK,QAAQ,YACZ,OAAM,IAAI,MACT;AAGF,UAAO,QAAQ,YAAY,mBAAmB;EAC9C;EAED;CACA;AACD"}
|
|
1
|
+
{"version":3,"file":"endpoint-hooks.cjs","names":["useMemo","useQuery","useMutation","useInfiniteQuery"],"sources":["../src/endpoint-hooks.ts"],"sourcesContent":["import type {\n\tQueryClient,\n\tQueryFunctionContext,\n\tUseInfiniteQueryOptions,\n\tUseInfiniteQueryResult,\n\tUseMutationOptions,\n\tUseMutationResult,\n\tUseQueryOptions,\n\tUseQueryResult,\n} from '@tanstack/react-query';\nimport { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport type {\n\tExtractEndpointResponse,\n\tFilteredRequestConfig,\n\tIsConfigRequired,\n\tMutationEndpoint,\n\tQueryEndpoint,\n\tTypedApiFunction,\n} from './types';\n\n/**\n * Build query key from endpoint and config\n */\nfunction buildQueryKey<Paths, T extends QueryEndpoint<Paths>>(\n\tendpoint: T,\n\tconfig?: FilteredRequestConfig<Paths, T>,\n): unknown[] {\n\tconst key: unknown[] = [endpoint];\n\n\tif (config && 'params' in config && config.params) {\n\t\tkey.push({ params: config.params });\n\t}\n\n\tif (config && 'query' in config && config.query) {\n\t\tkey.push({ query: config.query });\n\t}\n\n\treturn key;\n}\n\n/**\n * Options for creating endpoint-based hooks\n */\nexport interface CreateEndpointHooksOptions {\n\tqueryClient?: QueryClient;\n}\n\n/**\n * Hook options type that conditionally requires config\n */\ntype UseQueryArgs<Paths, T extends QueryEndpoint<Paths>> = IsConfigRequired<\n\tPaths,\n\tT\n> extends true\n\t? [\n\t\t\tconfig: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t]\n\t: [\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t];\n\n/**\n * Endpoint-based React Query hooks\n */\nexport interface EndpointHooks<Paths> {\n\t/**\n\t * Use query hook for GET endpoints.\n\t * Config is required when endpoint has path params.\n\t */\n\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\t...args: UseQueryArgs<Paths, T>\n\t) => UseQueryResult<ExtractEndpointResponse<Paths, T>, Error>;\n\n\t/**\n\t * Use mutation hook for POST, PUT, PATCH, DELETE endpoints.\n\t * Config with params/body is passed to mutate().\n\t */\n\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\toptions?: Omit<\n\t\t\tUseMutationOptions<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>,\n\t\t\t'mutationFn'\n\t\t>,\n\t) => UseMutationResult<\n\t\tExtractEndpointResponse<Paths, T>,\n\t\tError,\n\t\tFilteredRequestConfig<Paths, T>\n\t>;\n\n\t/**\n\t * Use infinite query hook for paginated GET endpoints.\n\t */\n\tuseInfiniteQuery: <\n\t\tT extends QueryEndpoint<Paths>,\n\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\tTPageParam = unknown,\n\t>(\n\t\tendpoint: T,\n\t\toptions: Omit<\n\t\t\tUseInfiniteQueryOptions<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>,\n\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t> & {\n\t\t\tgetNextPageParam: (\n\t\t\t\tlastPage: TPageData,\n\t\t\t\tallPages: TPageData[],\n\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\tallPageParams: TPageParam[],\n\t\t\t) => TPageParam | undefined;\n\t\t\tinitialPageParam: TPageParam;\n\t\t},\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => UseInfiniteQueryResult<\n\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\tError\n\t>;\n\n\t/**\n\t * Invalidate queries for a specific endpoint.\n\t */\n\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => Promise<void>;\n\n\t/**\n\t * Invalidate all queries in the cache.\n\t */\n\tinvalidateAllQueries: () => Promise<void>;\n\n\t/**\n\t * Build a query key for manual cache operations\n\t */\n\tbuildQueryKey: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => unknown[];\n}\n\n/**\n * Create endpoint-based React Query hooks from a typed fetcher.\n *\n * @example\n * ```typescript\n * const fetcher = createAuthAwareFetcher<paths>({ ... });\n * const hooks = createEndpointHooks<paths>(fetcher);\n *\n * // In a component\n * const { data } = hooks.useQuery('GET /users/{id}', { params: { id: '123' } });\n *\n * const mutation = hooks.useMutation('POST /users');\n * await mutation.mutateAsync({ body: { name: 'John' } });\n * ```\n */\nexport function createEndpointHooks<Paths>(\n\tfetcher: TypedApiFunction<Paths>,\n\toptions: CreateEndpointHooksOptions = {},\n): EndpointHooks<Paths> {\n\treturn {\n\t\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\t...args: UseQueryArgs<Paths, T>\n\t\t) => {\n\t\t\t// Parse args - config is first, options is second\n\t\t\tconst [config, queryOptions] = args as [\n\t\t\t\tFilteredRequestConfig<Paths, T> | undefined,\n\t\t\t\t(\n\t\t\t\t\t| Omit<\n\t\t\t\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t\t\t >\n\t\t\t\t\t| undefined\n\t\t\t\t),\n\t\t\t];\n\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: () =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...queryOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, queryOptions],\n\t\t\t);\n\n\t\t\treturn useQuery<ExtractEndpointResponse<Paths, T>, Error>(\n\t\t\t\tmemoizedOptions,\n\t\t\t);\n\t\t},\n\n\t\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tmutationOptions?: Omit<\n\t\t\t\tUseMutationOptions<\n\t\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\t\tError,\n\t\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t\t>,\n\t\t\t\t'mutationFn'\n\t\t\t>,\n\t\t) => {\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tmutationFn: (config: FilteredRequestConfig<Paths, T>) =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...mutationOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, fetcher, mutationOptions],\n\t\t\t);\n\n\t\t\treturn useMutation<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tuseInfiniteQuery: <\n\t\t\tT extends QueryEndpoint<Paths>,\n\t\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\t\tTPageParam = unknown,\n\t\t>(\n\t\t\tendpoint: T,\n\t\t\toptions: Omit<\n\t\t\t\tUseInfiniteQueryOptions<\n\t\t\t\t\tTPageData,\n\t\t\t\t\tError,\n\t\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\t\tunknown[],\n\t\t\t\t\tTPageParam\n\t\t\t\t>,\n\t\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t\t> & {\n\t\t\t\tgetNextPageParam: (\n\t\t\t\t\tlastPage: TPageData,\n\t\t\t\t\tallPages: TPageData[],\n\t\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\t\tallPageParams: TPageParam[],\n\t\t\t\t) => TPageParam | undefined;\n\t\t\t\tinitialPageParam: TPageParam;\n\t\t\t},\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: ({\n\t\t\t\t\t\tpageParam,\n\t\t\t\t\t}: QueryFunctionContext<unknown[], TPageParam>) => {\n\t\t\t\t\t\tlet mergedConfig = config;\n\t\t\t\t\t\tif (pageParam !== undefined && config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = {\n\t\t\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\t\tquery: { ...(config as any).query, ...pageQuery },\n\t\t\t\t\t\t\t} as any;\n\t\t\t\t\t\t} else if (pageParam !== undefined && !config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = { query: pageQuery } as any;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, mergedConfig) as Promise<TPageData>;\n\t\t\t\t\t},\n\t\t\t\t\t...options,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, options],\n\t\t\t);\n\n\t\t\treturn useInfiniteQuery<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\t\t\treturn options.queryClient.invalidateQueries({\n\t\t\t\tqueryKey,\n\t\t\t\texact: !!config,\n\t\t\t});\n\t\t},\n\n\t\tinvalidateAllQueries: () => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateAllQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn options.queryClient.invalidateQueries();\n\t\t},\n\n\t\tbuildQueryKey,\n\t};\n}\n"],"mappings":";;;;;;;AAwBA,SAAS,cACR,UACA,QACY;CACZ,MAAM,MAAiB,CAAC,QAAQ;CAEhC,IAAI,UAAU,YAAY,UAAU,OAAO,QAC1C,IAAI,KAAK,EAAE,QAAQ,OAAO,OAAO,CAAC;CAGnC,IAAI,UAAU,WAAW,UAAU,OAAO,OACzC,IAAI,KAAK,EAAE,OAAO,OAAO,MAAM,CAAC;CAGjC,OAAO;AACR;;;;;;;;;;;;;;;;AAsIA,SAAgB,oBACf,SACA,UAAsC,CAAC,GAChB;CACvB,OAAO;EACN,WACC,UACA,GAAG,SACC;GAEJ,MAAM,CAAC,QAAQ,gBAAgB;GAW/B,MAAM,WAAW,cAAc,UAAU,MAAM;GAE/C,MAAM,mBAAA,GAAkBA,MAAAA,QAAAA,QAChB;IACN;IACA,eAGE,QAIC,UAAU,MAAM;IACnB,GAAG;GACJ,IACA;IAAC;IAAU;IAAQ;IAAS;IAAU;GAAY,CACnD;GAEA,QAAA,GAAOC,sBAAAA,SAAAA,CACN,eACD;EACD;EAEA,cACC,UACA,oBAQI;GACJ,MAAM,mBAAA,GAAkBD,MAAAA,QAAAA,QAChB;IACN,aAAa,WAGX,QAIC,UAAU,MAAM;IACnB,GAAG;GACJ,IACA;IAAC;IAAU;IAAS;GAAe,CACpC;GAEA,QAAA,GAAOE,sBAAAA,YAAAA,CAIL,eAAe;EAClB;EAEA,mBAKC,UACA,SAkBA,WACI;GACJ,MAAM,WAAW,cAAc,UAAU,MAAM;GAE/C,MAAM,mBAAA,GAAkBF,MAAAA,QAAAA,QAChB;IACN;IACA,UAAU,EACT,gBACkD;KAClD,IAAI,eAAe;KACnB,IAAI,cAAc,KAAA,KAAa,QAAQ;MACtC,MAAM,YACL,OAAO,cAAc,WAAW,YAAY,EAAE,MAAM,UAAU;MAC/D,eAAe;OACd,GAAG;OACH,OAAO;QAAE,GAAI,OAAe;QAAO,GAAG;OAAU;MACjD;KACD,OAAO,IAAI,cAAc,KAAA,KAAa,CAAC,QAGtC,eAAe,EAAE,OADhB,OAAO,cAAc,WAAW,YAAY,EAAE,MAAM,UAAU,EAC7B;KAEnC,OACC,QAIC,UAAU,YAAY;IACzB;IACA,GAAG;GACJ,IACA;IAAC;IAAU;IAAQ;IAAS;IAAU;GAAO,CAC9C;GAEA,QAAA,GAAOG,sBAAAA,iBAAAA,CAML,eAAe;EAClB;EAEA,oBACC,UACA,WACI;GACJ,IAAI,CAAC,QAAQ,aACZ,MAAM,IAAI,MACT,wFACD;GAED,MAAM,WAAW,cAAc,UAAU,MAAM;GAC/C,OAAO,QAAQ,YAAY,kBAAkB;IAC5C;IACA,OAAO,CAAC,CAAC;GACV,CAAC;EACF;EAEA,4BAA4B;GAC3B,IAAI,CAAC,QAAQ,aACZ,MAAM,IAAI,MACT,2FACD;GAED,OAAO,QAAQ,YAAY,kBAAkB;EAC9C;EAEA;CACD;AACD"}
|
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
import { ExtractEndpointResponse, FilteredRequestConfig, IsConfigRequired, MutationEndpoint, QueryEndpoint, TypedApiFunction } from "./types
|
|
1
|
+
import { ExtractEndpointResponse, FilteredRequestConfig, IsConfigRequired, MutationEndpoint, QueryEndpoint, TypedApiFunction } from "./types.cjs";
|
|
2
2
|
import { QueryClient, UseInfiniteQueryOptions, UseInfiniteQueryResult, UseMutationOptions, UseMutationResult, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
|
|
3
|
-
|
|
4
3
|
//#region src/endpoint-hooks.d.ts
|
|
5
|
-
|
|
6
4
|
/**
|
|
7
5
|
* Options for creating endpoint-based hooks
|
|
8
6
|
*/
|
|
9
|
-
interface CreateEndpointHooksOptions {
|
|
7
|
+
export interface CreateEndpointHooksOptions {
|
|
10
8
|
queryClient?: QueryClient;
|
|
11
9
|
}
|
|
12
10
|
/**
|
|
@@ -16,7 +14,7 @@ type UseQueryArgs<Paths, T extends QueryEndpoint<Paths>> = IsConfigRequired<Path
|
|
|
16
14
|
/**
|
|
17
15
|
* Endpoint-based React Query hooks
|
|
18
16
|
*/
|
|
19
|
-
interface EndpointHooks<Paths> {
|
|
17
|
+
export interface EndpointHooks<Paths> {
|
|
20
18
|
/**
|
|
21
19
|
* Use query hook for GET endpoints.
|
|
22
20
|
* Config is required when endpoint has path params.
|
|
@@ -68,7 +66,6 @@ interface EndpointHooks<Paths> {
|
|
|
68
66
|
* await mutation.mutateAsync({ body: { name: 'John' } });
|
|
69
67
|
* ```
|
|
70
68
|
*/
|
|
71
|
-
declare function createEndpointHooks<Paths>(fetcher: TypedApiFunction<Paths>, options?: CreateEndpointHooksOptions): EndpointHooks<Paths>;
|
|
69
|
+
export declare function createEndpointHooks<Paths>(fetcher: TypedApiFunction<Paths>, options?: CreateEndpointHooksOptions): EndpointHooks<Paths>;
|
|
72
70
|
//#endregion
|
|
73
|
-
export { CreateEndpointHooksOptions, EndpointHooks, createEndpointHooks };
|
|
74
71
|
//# sourceMappingURL=endpoint-hooks.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-hooks.d.cts","names":[],"sources":["../src/endpoint-hooks.ts"],"
|
|
1
|
+
{"version":3,"file":"endpoint-hooks.d.cts","names":[],"sources":["../src/endpoint-hooks.ts"],"mappings":";;;;;;iBA4CiB;EAChB,cAAc;;;;;KAMV,aAAa,OAAO,UAAU,cAAc,UAAU,iBAC1D,OACA,mBAGE,QAAQ,sBAAsB,OAAO,IACrC,UAAU,KACT,gBAAgB,wBAAwB,OAAO,IAAI,oCAKpD,SAAS,sBAAsB,OAAO,IACtC,UAAU,KACT,gBAAgB,wBAAwB,OAAO,IAAI;;;;iBAQtC,cAAc;;;;;EAK9B,WAAW,UAAU,cAAc,QAClC,UAAU,MACP,MAAM,aAAa,OAAO,OACzB,eAAe,wBAAwB,OAAO,IAAI;;;;;EAMvD,cAAc,UAAU,iBAAiB,QACxC,UAAU,GACV,UAAU,KACT,mBACC,wBAAwB,OAAO,IAC/B,OACA,sBAAsB,OAAO,uBAI3B,kBACJ,wBAAwB,OAAO,IAC/B,OACA,sBAAsB,OAAO;;;;EAM9B,mBACC,UAAU,cAAc,QACxB,YAAY,wBAAwB,OAAO,IAC3C,sBAEA,UAAU,GACV,SAAS,KACR,wBACC,WACA;IACE,OAAO;IAAa,YAAY;gBAElC;IAID,mBACC,UAAU,WACV,UAAU,aACV,eAAe,YACf,eAAe,iBACX;IACL,kBAAkB;KAEnB,SAAS,sBAAsB,OAAO,OAClC;IACF,OAAO;IAAa,YAAY;KAClC;;;;EAMD,oBAAoB,UAAU,cAAc,QAC3C,UAAU,GACV,SAAS,sBAAsB,OAAO,OAClC;;;;EAKL,4BAA4B;;;;EAK5B,gBAAgB,UAAU,cAAc,QACvC,UAAU,GACV,SAAS,sBAAsB,OAAO;;;;;;;;;;;;;;;;;wBAmBxB,oBAAoB,OACnC,SAAS,iBAAiB,QAC1B,UAAS,6BACP,cAAc"}
|
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
import { ExtractEndpointResponse, FilteredRequestConfig, IsConfigRequired, MutationEndpoint, QueryEndpoint, TypedApiFunction } from "./types
|
|
1
|
+
import { ExtractEndpointResponse, FilteredRequestConfig, IsConfigRequired, MutationEndpoint, QueryEndpoint, TypedApiFunction } from "./types.mjs";
|
|
2
2
|
import { QueryClient, UseInfiniteQueryOptions, UseInfiniteQueryResult, UseMutationOptions, UseMutationResult, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
|
|
3
|
-
|
|
4
3
|
//#region src/endpoint-hooks.d.ts
|
|
5
|
-
|
|
6
4
|
/**
|
|
7
5
|
* Options for creating endpoint-based hooks
|
|
8
6
|
*/
|
|
9
|
-
interface CreateEndpointHooksOptions {
|
|
7
|
+
export interface CreateEndpointHooksOptions {
|
|
10
8
|
queryClient?: QueryClient;
|
|
11
9
|
}
|
|
12
10
|
/**
|
|
@@ -16,7 +14,7 @@ type UseQueryArgs<Paths, T extends QueryEndpoint<Paths>> = IsConfigRequired<Path
|
|
|
16
14
|
/**
|
|
17
15
|
* Endpoint-based React Query hooks
|
|
18
16
|
*/
|
|
19
|
-
interface EndpointHooks<Paths> {
|
|
17
|
+
export interface EndpointHooks<Paths> {
|
|
20
18
|
/**
|
|
21
19
|
* Use query hook for GET endpoints.
|
|
22
20
|
* Config is required when endpoint has path params.
|
|
@@ -68,7 +66,6 @@ interface EndpointHooks<Paths> {
|
|
|
68
66
|
* await mutation.mutateAsync({ body: { name: 'John' } });
|
|
69
67
|
* ```
|
|
70
68
|
*/
|
|
71
|
-
declare function createEndpointHooks<Paths>(fetcher: TypedApiFunction<Paths>, options?: CreateEndpointHooksOptions): EndpointHooks<Paths>;
|
|
69
|
+
export declare function createEndpointHooks<Paths>(fetcher: TypedApiFunction<Paths>, options?: CreateEndpointHooksOptions): EndpointHooks<Paths>;
|
|
72
70
|
//#endregion
|
|
73
|
-
export { CreateEndpointHooksOptions, EndpointHooks, createEndpointHooks };
|
|
74
71
|
//# sourceMappingURL=endpoint-hooks.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-hooks.d.mts","names":[],"sources":["../src/endpoint-hooks.ts"],"
|
|
1
|
+
{"version":3,"file":"endpoint-hooks.d.mts","names":[],"sources":["../src/endpoint-hooks.ts"],"mappings":";;;;;;iBA4CiB;EAChB,cAAc;;;;;KAMV,aAAa,OAAO,UAAU,cAAc,UAAU,iBAC1D,OACA,mBAGE,QAAQ,sBAAsB,OAAO,IACrC,UAAU,KACT,gBAAgB,wBAAwB,OAAO,IAAI,oCAKpD,SAAS,sBAAsB,OAAO,IACtC,UAAU,KACT,gBAAgB,wBAAwB,OAAO,IAAI;;;;iBAQtC,cAAc;;;;;EAK9B,WAAW,UAAU,cAAc,QAClC,UAAU,MACP,MAAM,aAAa,OAAO,OACzB,eAAe,wBAAwB,OAAO,IAAI;;;;;EAMvD,cAAc,UAAU,iBAAiB,QACxC,UAAU,GACV,UAAU,KACT,mBACC,wBAAwB,OAAO,IAC/B,OACA,sBAAsB,OAAO,uBAI3B,kBACJ,wBAAwB,OAAO,IAC/B,OACA,sBAAsB,OAAO;;;;EAM9B,mBACC,UAAU,cAAc,QACxB,YAAY,wBAAwB,OAAO,IAC3C,sBAEA,UAAU,GACV,SAAS,KACR,wBACC,WACA;IACE,OAAO;IAAa,YAAY;gBAElC;IAID,mBACC,UAAU,WACV,UAAU,aACV,eAAe,YACf,eAAe,iBACX;IACL,kBAAkB;KAEnB,SAAS,sBAAsB,OAAO,OAClC;IACF,OAAO;IAAa,YAAY;KAClC;;;;EAMD,oBAAoB,UAAU,cAAc,QAC3C,UAAU,GACV,SAAS,sBAAsB,OAAO,OAClC;;;;EAKL,4BAA4B;;;;EAK5B,gBAAgB,UAAU,cAAc,QACvC,UAAU,GACV,SAAS,sBAAsB,OAAO;;;;;;;;;;;;;;;;;wBAmBxB,oBAAoB,OACnC,SAAS,iBAAiB,QAC1B,UAAS,6BACP,cAAc"}
|
package/dist/endpoint-hooks.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";
|
|
2
2
|
import { useMemo } from "react";
|
|
3
|
-
|
|
4
3
|
//#region src/endpoint-hooks.ts
|
|
5
4
|
/**
|
|
6
5
|
* Build query key from endpoint and config
|
|
@@ -55,7 +54,7 @@ function createEndpointHooks(fetcher, options = {}) {
|
|
|
55
54
|
]);
|
|
56
55
|
return useMutation(memoizedOptions);
|
|
57
56
|
},
|
|
58
|
-
useInfiniteQuery: (endpoint, options
|
|
57
|
+
useInfiniteQuery: (endpoint, options, config) => {
|
|
59
58
|
const queryKey = buildQueryKey(endpoint, config);
|
|
60
59
|
const memoizedOptions = useMemo(() => ({
|
|
61
60
|
queryKey,
|
|
@@ -70,19 +69,16 @@ function createEndpointHooks(fetcher, options = {}) {
|
|
|
70
69
|
...pageQuery
|
|
71
70
|
}
|
|
72
71
|
};
|
|
73
|
-
} else if (pageParam !== void 0 && !config) {
|
|
74
|
-
const pageQuery = typeof pageParam === "object" ? pageParam : { page: pageParam };
|
|
75
|
-
mergedConfig = { query: pageQuery };
|
|
76
|
-
}
|
|
72
|
+
} else if (pageParam !== void 0 && !config) mergedConfig = { query: typeof pageParam === "object" ? pageParam : { page: pageParam } };
|
|
77
73
|
return fetcher(endpoint, mergedConfig);
|
|
78
74
|
},
|
|
79
|
-
...options
|
|
75
|
+
...options
|
|
80
76
|
}), [
|
|
81
77
|
endpoint,
|
|
82
78
|
config,
|
|
83
79
|
fetcher,
|
|
84
80
|
queryKey,
|
|
85
|
-
options
|
|
81
|
+
options
|
|
86
82
|
]);
|
|
87
83
|
return useInfiniteQuery(memoizedOptions);
|
|
88
84
|
},
|
|
@@ -101,7 +97,7 @@ function createEndpointHooks(fetcher, options = {}) {
|
|
|
101
97
|
buildQueryKey
|
|
102
98
|
};
|
|
103
99
|
}
|
|
104
|
-
|
|
105
100
|
//#endregion
|
|
106
101
|
export { createEndpointHooks };
|
|
102
|
+
|
|
107
103
|
//# sourceMappingURL=endpoint-hooks.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-hooks.mjs","names":["endpoint: T","config?: FilteredRequestConfig<Paths, T>","key: unknown[]","fetcher: TypedApiFunction<Paths>","options: CreateEndpointHooksOptions","mutationOptions?: Omit<\n\t\t\t\tUseMutationOptions<\n\t\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\t\tError,\n\t\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t\t>,\n\t\t\t\t'mutationFn'\n\t\t\t>","config: FilteredRequestConfig<Paths, T>","options: Omit<\n\t\t\t\tUseInfiniteQueryOptions<\n\t\t\t\t\tTPageData,\n\t\t\t\t\tError,\n\t\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\t\tunknown[],\n\t\t\t\t\tTPageParam\n\t\t\t\t>,\n\t\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t\t> & {\n\t\t\t\tgetNextPageParam: (\n\t\t\t\t\tlastPage: TPageData,\n\t\t\t\t\tallPages: TPageData[],\n\t\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\t\tallPageParams: TPageParam[],\n\t\t\t\t) => TPageParam | undefined;\n\t\t\t\tinitialPageParam: TPageParam;\n\t\t\t}","options"],"sources":["../src/endpoint-hooks.ts"],"sourcesContent":["import type {\n\tQueryClient,\n\tQueryFunctionContext,\n\tUseInfiniteQueryOptions,\n\tUseInfiniteQueryResult,\n\tUseMutationOptions,\n\tUseMutationResult,\n\tUseQueryOptions,\n\tUseQueryResult,\n} from '@tanstack/react-query';\nimport { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport type {\n\tExtractEndpointResponse,\n\tFilteredRequestConfig,\n\tIsConfigRequired,\n\tMutationEndpoint,\n\tQueryEndpoint,\n\tTypedApiFunction,\n} from './types';\n\n/**\n * Build query key from endpoint and config\n */\nfunction buildQueryKey<Paths, T extends QueryEndpoint<Paths>>(\n\tendpoint: T,\n\tconfig?: FilteredRequestConfig<Paths, T>,\n): unknown[] {\n\tconst key: unknown[] = [endpoint];\n\n\tif (config && 'params' in config && config.params) {\n\t\tkey.push({ params: config.params });\n\t}\n\n\tif (config && 'query' in config && config.query) {\n\t\tkey.push({ query: config.query });\n\t}\n\n\treturn key;\n}\n\n/**\n * Options for creating endpoint-based hooks\n */\nexport interface CreateEndpointHooksOptions {\n\tqueryClient?: QueryClient;\n}\n\n/**\n * Hook options type that conditionally requires config\n */\ntype UseQueryArgs<Paths, T extends QueryEndpoint<Paths>> = IsConfigRequired<\n\tPaths,\n\tT\n> extends true\n\t? [\n\t\t\tconfig: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t]\n\t: [\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t];\n\n/**\n * Endpoint-based React Query hooks\n */\nexport interface EndpointHooks<Paths> {\n\t/**\n\t * Use query hook for GET endpoints.\n\t * Config is required when endpoint has path params.\n\t */\n\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\t...args: UseQueryArgs<Paths, T>\n\t) => UseQueryResult<ExtractEndpointResponse<Paths, T>, Error>;\n\n\t/**\n\t * Use mutation hook for POST, PUT, PATCH, DELETE endpoints.\n\t * Config with params/body is passed to mutate().\n\t */\n\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\toptions?: Omit<\n\t\t\tUseMutationOptions<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>,\n\t\t\t'mutationFn'\n\t\t>,\n\t) => UseMutationResult<\n\t\tExtractEndpointResponse<Paths, T>,\n\t\tError,\n\t\tFilteredRequestConfig<Paths, T>\n\t>;\n\n\t/**\n\t * Use infinite query hook for paginated GET endpoints.\n\t */\n\tuseInfiniteQuery: <\n\t\tT extends QueryEndpoint<Paths>,\n\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\tTPageParam = unknown,\n\t>(\n\t\tendpoint: T,\n\t\toptions: Omit<\n\t\t\tUseInfiniteQueryOptions<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>,\n\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t> & {\n\t\t\tgetNextPageParam: (\n\t\t\t\tlastPage: TPageData,\n\t\t\t\tallPages: TPageData[],\n\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\tallPageParams: TPageParam[],\n\t\t\t) => TPageParam | undefined;\n\t\t\tinitialPageParam: TPageParam;\n\t\t},\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => UseInfiniteQueryResult<\n\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\tError\n\t>;\n\n\t/**\n\t * Invalidate queries for a specific endpoint.\n\t */\n\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => Promise<void>;\n\n\t/**\n\t * Invalidate all queries in the cache.\n\t */\n\tinvalidateAllQueries: () => Promise<void>;\n\n\t/**\n\t * Build a query key for manual cache operations\n\t */\n\tbuildQueryKey: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => unknown[];\n}\n\n/**\n * Create endpoint-based React Query hooks from a typed fetcher.\n *\n * @example\n * ```typescript\n * const fetcher = createAuthAwareFetcher<paths>({ ... });\n * const hooks = createEndpointHooks<paths>(fetcher);\n *\n * // In a component\n * const { data } = hooks.useQuery('GET /users/{id}', { params: { id: '123' } });\n *\n * const mutation = hooks.useMutation('POST /users');\n * await mutation.mutateAsync({ body: { name: 'John' } });\n * ```\n */\nexport function createEndpointHooks<Paths>(\n\tfetcher: TypedApiFunction<Paths>,\n\toptions: CreateEndpointHooksOptions = {},\n): EndpointHooks<Paths> {\n\treturn {\n\t\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\t...args: UseQueryArgs<Paths, T>\n\t\t) => {\n\t\t\t// Parse args - config is first, options is second\n\t\t\tconst [config, queryOptions] = args as [\n\t\t\t\tFilteredRequestConfig<Paths, T> | undefined,\n\t\t\t\t(\n\t\t\t\t\t| Omit<\n\t\t\t\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t\t\t >\n\t\t\t\t\t| undefined\n\t\t\t\t),\n\t\t\t];\n\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: () =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...queryOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, queryOptions],\n\t\t\t);\n\n\t\t\treturn useQuery<ExtractEndpointResponse<Paths, T>, Error>(\n\t\t\t\tmemoizedOptions,\n\t\t\t);\n\t\t},\n\n\t\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tmutationOptions?: Omit<\n\t\t\t\tUseMutationOptions<\n\t\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\t\tError,\n\t\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t\t>,\n\t\t\t\t'mutationFn'\n\t\t\t>,\n\t\t) => {\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tmutationFn: (config: FilteredRequestConfig<Paths, T>) =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...mutationOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, fetcher, mutationOptions],\n\t\t\t);\n\n\t\t\treturn useMutation<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tuseInfiniteQuery: <\n\t\t\tT extends QueryEndpoint<Paths>,\n\t\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\t\tTPageParam = unknown,\n\t\t>(\n\t\t\tendpoint: T,\n\t\t\toptions: Omit<\n\t\t\t\tUseInfiniteQueryOptions<\n\t\t\t\t\tTPageData,\n\t\t\t\t\tError,\n\t\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\t\tunknown[],\n\t\t\t\t\tTPageParam\n\t\t\t\t>,\n\t\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t\t> & {\n\t\t\t\tgetNextPageParam: (\n\t\t\t\t\tlastPage: TPageData,\n\t\t\t\t\tallPages: TPageData[],\n\t\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\t\tallPageParams: TPageParam[],\n\t\t\t\t) => TPageParam | undefined;\n\t\t\t\tinitialPageParam: TPageParam;\n\t\t\t},\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: ({\n\t\t\t\t\t\tpageParam,\n\t\t\t\t\t}: QueryFunctionContext<unknown[], TPageParam>) => {\n\t\t\t\t\t\tlet mergedConfig = config;\n\t\t\t\t\t\tif (pageParam !== undefined && config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = {\n\t\t\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\t\tquery: { ...(config as any).query, ...pageQuery },\n\t\t\t\t\t\t\t} as any;\n\t\t\t\t\t\t} else if (pageParam !== undefined && !config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = { query: pageQuery } as any;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, mergedConfig) as Promise<TPageData>;\n\t\t\t\t\t},\n\t\t\t\t\t...options,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, options],\n\t\t\t);\n\n\t\t\treturn useInfiniteQuery<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\t\t\treturn options.queryClient.invalidateQueries({\n\t\t\t\tqueryKey,\n\t\t\t\texact: !!config,\n\t\t\t});\n\t\t},\n\n\t\tinvalidateAllQueries: () => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateAllQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn options.queryClient.invalidateQueries();\n\t\t},\n\n\t\tbuildQueryKey,\n\t};\n}\n"],"mappings":";;;;;;;AAwBA,SAAS,cACRA,UACAC,QACY;CACZ,MAAMC,MAAiB,CAAC,QAAS;AAEjC,KAAI,UAAU,YAAY,UAAU,OAAO,OAC1C,KAAI,KAAK,EAAE,QAAQ,OAAO,OAAQ,EAAC;AAGpC,KAAI,UAAU,WAAW,UAAU,OAAO,MACzC,KAAI,KAAK,EAAE,OAAO,OAAO,MAAO,EAAC;AAGlC,QAAO;AACP;;;;;;;;;;;;;;;;AAsID,SAAgB,oBACfC,SACAC,UAAsC,CAAE,GACjB;AACvB,QAAO;EACN,UAAU,CACTJ,UACA,GAAG,SACC;GAEJ,MAAM,CAAC,QAAQ,aAAa,GAAG;GAW/B,MAAM,WAAW,cAAc,UAAU,OAAO;GAEhD,MAAM,kBAAkB,QACvB,OAAO;IACN;IACA,SAAS,MAER,AACC,QAIC,UAAU,OAAO;IACpB,GAAG;GACH,IACD;IAAC;IAAU;IAAQ;IAAS;IAAU;GAAa,EACnD;AAED,UAAO,SACN,gBACA;EACD;EAED,aAAa,CACZA,UACAK,oBAQI;GACJ,MAAM,kBAAkB,QACvB,OAAO;IACN,YAAY,CAACC,WAEZ,AACC,QAIC,UAAU,OAAO;IACpB,GAAG;GACH,IACD;IAAC;IAAU;IAAS;GAAgB,EACpC;AAED,UAAO,YAIL,gBAAgB;EAClB;EAED,kBAAkB,CAKjBN,UACAO,WAkBAN,WACI;GACJ,MAAM,WAAW,cAAc,UAAU,OAAO;GAEhD,MAAM,kBAAkB,QACvB,OAAO;IACN;IACA,SAAS,CAAC,EACT,WAC6C,KAAK;KAClD,IAAI,eAAe;AACnB,SAAI,wBAA2B,QAAQ;MACtC,MAAM,mBACE,cAAc,WAAW,YAAY,EAAE,MAAM,UAAW;AAChE,qBAAe;OACd,GAAG;OACH,OAAO;QAAE,GAAI,OAAe;QAAO,GAAG;OAAW;MACjD;KACD,WAAU,yBAA4B,QAAQ;MAC9C,MAAM,mBACE,cAAc,WAAW,YAAY,EAAE,MAAM,UAAW;AAChE,qBAAe,EAAE,OAAO,UAAW;KACnC;AACD,YAAO,AACN,QAIC,UAAU,aAAa;IACzB;IACD,GAAGO;GACH,IACD;IAAC;IAAU;IAAQ;IAAS;IAAUA;GAAQ,EAC9C;AAED,UAAO,iBAML,gBAAgB;EAClB;EAED,mBAAmB,CAClBR,UACAC,WACI;AACJ,QAAK,QAAQ,YACZ,OAAM,IAAI,MACT;GAGF,MAAM,WAAW,cAAc,UAAU,OAAO;AAChD,UAAO,QAAQ,YAAY,kBAAkB;IAC5C;IACA,SAAS;GACT,EAAC;EACF;EAED,sBAAsB,MAAM;AAC3B,QAAK,QAAQ,YACZ,OAAM,IAAI,MACT;AAGF,UAAO,QAAQ,YAAY,mBAAmB;EAC9C;EAED;CACA;AACD"}
|
|
1
|
+
{"version":3,"file":"endpoint-hooks.mjs","names":[],"sources":["../src/endpoint-hooks.ts"],"sourcesContent":["import type {\n\tQueryClient,\n\tQueryFunctionContext,\n\tUseInfiniteQueryOptions,\n\tUseInfiniteQueryResult,\n\tUseMutationOptions,\n\tUseMutationResult,\n\tUseQueryOptions,\n\tUseQueryResult,\n} from '@tanstack/react-query';\nimport { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport type {\n\tExtractEndpointResponse,\n\tFilteredRequestConfig,\n\tIsConfigRequired,\n\tMutationEndpoint,\n\tQueryEndpoint,\n\tTypedApiFunction,\n} from './types';\n\n/**\n * Build query key from endpoint and config\n */\nfunction buildQueryKey<Paths, T extends QueryEndpoint<Paths>>(\n\tendpoint: T,\n\tconfig?: FilteredRequestConfig<Paths, T>,\n): unknown[] {\n\tconst key: unknown[] = [endpoint];\n\n\tif (config && 'params' in config && config.params) {\n\t\tkey.push({ params: config.params });\n\t}\n\n\tif (config && 'query' in config && config.query) {\n\t\tkey.push({ query: config.query });\n\t}\n\n\treturn key;\n}\n\n/**\n * Options for creating endpoint-based hooks\n */\nexport interface CreateEndpointHooksOptions {\n\tqueryClient?: QueryClient;\n}\n\n/**\n * Hook options type that conditionally requires config\n */\ntype UseQueryArgs<Paths, T extends QueryEndpoint<Paths>> = IsConfigRequired<\n\tPaths,\n\tT\n> extends true\n\t? [\n\t\t\tconfig: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t]\n\t: [\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t\toptions?: Omit<\n\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t>,\n\t\t];\n\n/**\n * Endpoint-based React Query hooks\n */\nexport interface EndpointHooks<Paths> {\n\t/**\n\t * Use query hook for GET endpoints.\n\t * Config is required when endpoint has path params.\n\t */\n\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\t...args: UseQueryArgs<Paths, T>\n\t) => UseQueryResult<ExtractEndpointResponse<Paths, T>, Error>;\n\n\t/**\n\t * Use mutation hook for POST, PUT, PATCH, DELETE endpoints.\n\t * Config with params/body is passed to mutate().\n\t */\n\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\toptions?: Omit<\n\t\t\tUseMutationOptions<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>,\n\t\t\t'mutationFn'\n\t\t>,\n\t) => UseMutationResult<\n\t\tExtractEndpointResponse<Paths, T>,\n\t\tError,\n\t\tFilteredRequestConfig<Paths, T>\n\t>;\n\n\t/**\n\t * Use infinite query hook for paginated GET endpoints.\n\t */\n\tuseInfiniteQuery: <\n\t\tT extends QueryEndpoint<Paths>,\n\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\tTPageParam = unknown,\n\t>(\n\t\tendpoint: T,\n\t\toptions: Omit<\n\t\t\tUseInfiniteQueryOptions<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>,\n\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t> & {\n\t\t\tgetNextPageParam: (\n\t\t\t\tlastPage: TPageData,\n\t\t\t\tallPages: TPageData[],\n\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\tallPageParams: TPageParam[],\n\t\t\t) => TPageParam | undefined;\n\t\t\tinitialPageParam: TPageParam;\n\t\t},\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => UseInfiniteQueryResult<\n\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\tError\n\t>;\n\n\t/**\n\t * Invalidate queries for a specific endpoint.\n\t */\n\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => Promise<void>;\n\n\t/**\n\t * Invalidate all queries in the cache.\n\t */\n\tinvalidateAllQueries: () => Promise<void>;\n\n\t/**\n\t * Build a query key for manual cache operations\n\t */\n\tbuildQueryKey: <T extends QueryEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => unknown[];\n}\n\n/**\n * Create endpoint-based React Query hooks from a typed fetcher.\n *\n * @example\n * ```typescript\n * const fetcher = createAuthAwareFetcher<paths>({ ... });\n * const hooks = createEndpointHooks<paths>(fetcher);\n *\n * // In a component\n * const { data } = hooks.useQuery('GET /users/{id}', { params: { id: '123' } });\n *\n * const mutation = hooks.useMutation('POST /users');\n * await mutation.mutateAsync({ body: { name: 'John' } });\n * ```\n */\nexport function createEndpointHooks<Paths>(\n\tfetcher: TypedApiFunction<Paths>,\n\toptions: CreateEndpointHooksOptions = {},\n): EndpointHooks<Paths> {\n\treturn {\n\t\tuseQuery: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\t...args: UseQueryArgs<Paths, T>\n\t\t) => {\n\t\t\t// Parse args - config is first, options is second\n\t\t\tconst [config, queryOptions] = args as [\n\t\t\t\tFilteredRequestConfig<Paths, T> | undefined,\n\t\t\t\t(\n\t\t\t\t\t| Omit<\n\t\t\t\t\t\t\tUseQueryOptions<ExtractEndpointResponse<Paths, T>, Error>,\n\t\t\t\t\t\t\t'queryKey' | 'queryFn'\n\t\t\t\t\t >\n\t\t\t\t\t| undefined\n\t\t\t\t),\n\t\t\t];\n\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: () =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...queryOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, queryOptions],\n\t\t\t);\n\n\t\t\treturn useQuery<ExtractEndpointResponse<Paths, T>, Error>(\n\t\t\t\tmemoizedOptions,\n\t\t\t);\n\t\t},\n\n\t\tuseMutation: <T extends MutationEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tmutationOptions?: Omit<\n\t\t\t\tUseMutationOptions<\n\t\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\t\tError,\n\t\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t\t>,\n\t\t\t\t'mutationFn'\n\t\t\t>,\n\t\t) => {\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tmutationFn: (config: FilteredRequestConfig<Paths, T>) =>\n\t\t\t\t\t\t// Type assertion needed due to complex conditional types\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, config),\n\t\t\t\t\t...mutationOptions,\n\t\t\t\t}),\n\t\t\t\t[endpoint, fetcher, mutationOptions],\n\t\t\t);\n\n\t\t\treturn useMutation<\n\t\t\t\tExtractEndpointResponse<Paths, T>,\n\t\t\t\tError,\n\t\t\t\tFilteredRequestConfig<Paths, T>\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tuseInfiniteQuery: <\n\t\t\tT extends QueryEndpoint<Paths>,\n\t\t\tTPageData = ExtractEndpointResponse<Paths, T>,\n\t\t\tTPageParam = unknown,\n\t\t>(\n\t\t\tendpoint: T,\n\t\t\toptions: Omit<\n\t\t\t\tUseInfiniteQueryOptions<\n\t\t\t\t\tTPageData,\n\t\t\t\t\tError,\n\t\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\t\tunknown[],\n\t\t\t\t\tTPageParam\n\t\t\t\t>,\n\t\t\t\t'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'\n\t\t\t> & {\n\t\t\t\tgetNextPageParam: (\n\t\t\t\t\tlastPage: TPageData,\n\t\t\t\t\tallPages: TPageData[],\n\t\t\t\t\tlastPageParam: TPageParam,\n\t\t\t\t\tallPageParams: TPageParam[],\n\t\t\t\t) => TPageParam | undefined;\n\t\t\t\tinitialPageParam: TPageParam;\n\t\t\t},\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\n\t\t\tconst memoizedOptions = useMemo(\n\t\t\t\t() => ({\n\t\t\t\t\tqueryKey,\n\t\t\t\t\tqueryFn: ({\n\t\t\t\t\t\tpageParam,\n\t\t\t\t\t}: QueryFunctionContext<unknown[], TPageParam>) => {\n\t\t\t\t\t\tlet mergedConfig = config;\n\t\t\t\t\t\tif (pageParam !== undefined && config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = {\n\t\t\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\t\tquery: { ...(config as any).query, ...pageQuery },\n\t\t\t\t\t\t\t} as any;\n\t\t\t\t\t\t} else if (pageParam !== undefined && !config) {\n\t\t\t\t\t\t\tconst pageQuery =\n\t\t\t\t\t\t\t\ttypeof pageParam === 'object' ? pageParam : { page: pageParam };\n\t\t\t\t\t\t\tmergedConfig = { query: pageQuery } as any;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tfetcher as (\n\t\t\t\t\t\t\t\tendpoint: T,\n\t\t\t\t\t\t\t\tconfig?: unknown,\n\t\t\t\t\t\t\t) => Promise<ExtractEndpointResponse<Paths, T>>\n\t\t\t\t\t\t)(endpoint, mergedConfig) as Promise<TPageData>;\n\t\t\t\t\t},\n\t\t\t\t\t...options,\n\t\t\t\t}),\n\t\t\t\t[endpoint, config, fetcher, queryKey, options],\n\t\t\t);\n\n\t\t\treturn useInfiniteQuery<\n\t\t\t\tTPageData,\n\t\t\t\tError,\n\t\t\t\t{ pages: TPageData[]; pageParams: TPageParam[] },\n\t\t\t\tunknown[],\n\t\t\t\tTPageParam\n\t\t\t>(memoizedOptions);\n\t\t},\n\n\t\tinvalidateQueries: <T extends QueryEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t) => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst queryKey = buildQueryKey(endpoint, config);\n\t\t\treturn options.queryClient.invalidateQueries({\n\t\t\t\tqueryKey,\n\t\t\t\texact: !!config,\n\t\t\t});\n\t\t},\n\n\t\tinvalidateAllQueries: () => {\n\t\t\tif (!options.queryClient) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'queryClient is required for invalidateAllQueries. Pass it to createEndpointHooks options.',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn options.queryClient.invalidateQueries();\n\t\t},\n\n\t\tbuildQueryKey,\n\t};\n}\n"],"mappings":";;;;;;AAwBA,SAAS,cACR,UACA,QACY;CACZ,MAAM,MAAiB,CAAC,QAAQ;CAEhC,IAAI,UAAU,YAAY,UAAU,OAAO,QAC1C,IAAI,KAAK,EAAE,QAAQ,OAAO,OAAO,CAAC;CAGnC,IAAI,UAAU,WAAW,UAAU,OAAO,OACzC,IAAI,KAAK,EAAE,OAAO,OAAO,MAAM,CAAC;CAGjC,OAAO;AACR;;;;;;;;;;;;;;;;AAsIA,SAAgB,oBACf,SACA,UAAsC,CAAC,GAChB;CACvB,OAAO;EACN,WACC,UACA,GAAG,SACC;GAEJ,MAAM,CAAC,QAAQ,gBAAgB;GAW/B,MAAM,WAAW,cAAc,UAAU,MAAM;GAE/C,MAAM,kBAAkB,eAChB;IACN;IACA,eAGE,QAIC,UAAU,MAAM;IACnB,GAAG;GACJ,IACA;IAAC;IAAU;IAAQ;IAAS;IAAU;GAAY,CACnD;GAEA,OAAO,SACN,eACD;EACD;EAEA,cACC,UACA,oBAQI;GACJ,MAAM,kBAAkB,eAChB;IACN,aAAa,WAGX,QAIC,UAAU,MAAM;IACnB,GAAG;GACJ,IACA;IAAC;IAAU;IAAS;GAAe,CACpC;GAEA,OAAO,YAIL,eAAe;EAClB;EAEA,mBAKC,UACA,SAkBA,WACI;GACJ,MAAM,WAAW,cAAc,UAAU,MAAM;GAE/C,MAAM,kBAAkB,eAChB;IACN;IACA,UAAU,EACT,gBACkD;KAClD,IAAI,eAAe;KACnB,IAAI,cAAc,KAAA,KAAa,QAAQ;MACtC,MAAM,YACL,OAAO,cAAc,WAAW,YAAY,EAAE,MAAM,UAAU;MAC/D,eAAe;OACd,GAAG;OACH,OAAO;QAAE,GAAI,OAAe;QAAO,GAAG;OAAU;MACjD;KACD,OAAO,IAAI,cAAc,KAAA,KAAa,CAAC,QAGtC,eAAe,EAAE,OADhB,OAAO,cAAc,WAAW,YAAY,EAAE,MAAM,UAAU,EAC7B;KAEnC,OACC,QAIC,UAAU,YAAY;IACzB;IACA,GAAG;GACJ,IACA;IAAC;IAAU;IAAQ;IAAS;IAAU;GAAO,CAC9C;GAEA,OAAO,iBAML,eAAe;EAClB;EAEA,oBACC,UACA,WACI;GACJ,IAAI,CAAC,QAAQ,aACZ,MAAM,IAAI,MACT,wFACD;GAED,MAAM,WAAW,cAAc,UAAU,MAAM;GAC/C,OAAO,QAAQ,YAAY,kBAAkB;IAC5C;IACA,OAAO,CAAC,CAAC;GACV,CAAC;EACF;EAEA,4BAA4B;GAC3B,IAAI,CAAC,QAAQ,aACZ,MAAM,IAAI,MACT,2FACD;GAED,OAAO,QAAQ,YAAY,kBAAkB;EAC9C;EAEA;CACD;AACD"}
|
package/dist/fetcher.cjs
CHANGED
|
@@ -1,4 +1,111 @@
|
|
|
1
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region \0rolldown/runtime.js
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
//#endregion
|
|
24
|
+
let qs = require("qs");
|
|
25
|
+
qs = __toESM(qs, 1);
|
|
26
|
+
//#region src/fetcher.ts
|
|
27
|
+
var TypedFetcher = class TypedFetcher {
|
|
28
|
+
baseURL;
|
|
29
|
+
defaultHeaders;
|
|
30
|
+
options;
|
|
31
|
+
fetchFn;
|
|
32
|
+
static getFetchFn(fn) {
|
|
33
|
+
if (fn) return fn;
|
|
34
|
+
if (typeof window !== "undefined" && typeof window.fetch === "function") return window.fetch.bind(window);
|
|
35
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.fetch === "function") return globalThis.fetch.bind(globalThis);
|
|
36
|
+
throw new Error("No fetch implementation found");
|
|
37
|
+
}
|
|
38
|
+
constructor(options = {}) {
|
|
39
|
+
this.baseURL = options.baseURL || "";
|
|
40
|
+
this.defaultHeaders = options.headers || {};
|
|
41
|
+
this.options = options;
|
|
42
|
+
this.fetchFn = TypedFetcher.getFetchFn(options.fetch);
|
|
43
|
+
}
|
|
44
|
+
async request(endpoint, config) {
|
|
45
|
+
const { method, route } = this.parseEndpoint(endpoint);
|
|
46
|
+
let url = route;
|
|
47
|
+
if (config && "params" in config && config.params) Object.entries(config.params).forEach(([key, value]) => {
|
|
48
|
+
url = url.replace(`{${key}}`, encodeURIComponent(String(value)));
|
|
49
|
+
});
|
|
50
|
+
if (config && "query" in config && config.query) {
|
|
51
|
+
const queryString = qs.default.stringify(config.query, {
|
|
52
|
+
encode: true,
|
|
53
|
+
arrayFormat: "brackets",
|
|
54
|
+
skipNulls: true
|
|
55
|
+
});
|
|
56
|
+
if (queryString) url += `?${queryString}`;
|
|
57
|
+
}
|
|
58
|
+
let requestConfig = {
|
|
59
|
+
method: method.toUpperCase(),
|
|
60
|
+
headers: {
|
|
61
|
+
...this.defaultHeaders,
|
|
62
|
+
...config && "headers" in config && config.headers || {}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
if (config && "body" in config && config.body) {
|
|
66
|
+
requestConfig.body = JSON.stringify(config.body);
|
|
67
|
+
requestConfig.headers = {
|
|
68
|
+
...requestConfig.headers,
|
|
69
|
+
"Content-Type": "application/json"
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
if (this.options.onRequest) requestConfig = await this.options.onRequest(requestConfig);
|
|
73
|
+
try {
|
|
74
|
+
let response = await this.fetchFn(`${this.baseURL}${url}`, requestConfig);
|
|
75
|
+
if (this.options.onResponse) response = await this.options.onResponse(response);
|
|
76
|
+
if (!response.ok) throw response;
|
|
77
|
+
if (response.status === 204 || response.headers.get("content-length") === "0") return;
|
|
78
|
+
return await response.json();
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (this.options.onError) await this.options.onError(error);
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
wrap(onError) {
|
|
85
|
+
return (endpoint, config) => this.request(endpoint, config).then((data) => ({
|
|
86
|
+
ok: true,
|
|
87
|
+
data
|
|
88
|
+
}), async (error) => ({
|
|
89
|
+
ok: false,
|
|
90
|
+
error: onError ? await onError(error) : error
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
parseEndpoint(endpoint) {
|
|
94
|
+
const [method, ...routeParts] = endpoint.split(" ");
|
|
95
|
+
const route = routeParts.join(" ");
|
|
96
|
+
return {
|
|
97
|
+
method: method?.toLowerCase() ?? "",
|
|
98
|
+
route
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
function createTypedFetcher(options) {
|
|
103
|
+
const fetcher = new TypedFetcher(options);
|
|
104
|
+
const fn = (endpoint, config) => fetcher.request(endpoint, config);
|
|
105
|
+
return Object.assign(fn, { wrap: (onError) => Object.assign(fetcher.wrap(onError), fn, { wrap: void 0 }) });
|
|
106
|
+
}
|
|
107
|
+
//#endregion
|
|
108
|
+
exports.TypedFetcher = TypedFetcher;
|
|
109
|
+
exports.createTypedFetcher = createTypedFetcher;
|
|
2
110
|
|
|
3
|
-
|
|
4
|
-
exports.createTypedFetcher = require_fetcher.createTypedFetcher;
|
|
111
|
+
//# sourceMappingURL=fetcher.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetcher.cjs","names":[],"sources":["../src/fetcher.ts"],"sourcesContent":["import qs from 'qs';\nimport type {\n\tEndpointString,\n\tErrorTransformer,\n\tExtractEndpointResponse,\n\tFetcherOptions,\n\tFilteredRequestConfig,\n\tParseEndpoint,\n\tTypedEndpoint,\n\tWrappedResult,\n} from './types';\n\nexport type { FetcherOptions, WrappedResult } from './types';\n\nexport class TypedFetcher<Paths> {\n\tprivate baseURL: string;\n\tprivate defaultHeaders: Record<string, string>;\n\tprivate options: FetcherOptions;\n\tprivate fetchFn: FetchFn;\n\n\tstatic getFetchFn(fn?: FetchFn): FetchFn {\n\t\tif (fn) {\n\t\t\treturn fn;\n\t\t}\n\n\t\tif (typeof window !== 'undefined' && typeof window.fetch === 'function') {\n\t\t\treturn window.fetch.bind(window);\n\t\t}\n\n\t\tif (\n\t\t\ttypeof globalThis !== 'undefined' &&\n\t\t\ttypeof globalThis.fetch === 'function'\n\t\t) {\n\t\t\treturn globalThis.fetch.bind(globalThis);\n\t\t}\n\n\t\tthrow new Error('No fetch implementation found');\n\t}\n\n\tconstructor(options: FetcherOptions = {}) {\n\t\tthis.baseURL = options.baseURL || '';\n\t\tthis.defaultHeaders = options.headers || {};\n\t\tthis.options = options;\n\t\tthis.fetchFn = TypedFetcher.getFetchFn(options.fetch);\n\t}\n\n\tasync request<T extends TypedEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t): Promise<ExtractEndpointResponse<Paths, T>> {\n\t\tconst { method, route } = this.parseEndpoint(endpoint);\n\n\t\t// Replace path parameters\n\t\tlet url = route;\n\t\tif (config && 'params' in config && config.params) {\n\t\t\tObject.entries(config.params as Record<string, unknown>).forEach(\n\t\t\t\t([key, value]) => {\n\t\t\t\t\turl = url.replace(`{${key}}`, encodeURIComponent(String(value)));\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\t// Add query parameters\n\t\tif (config && 'query' in config && config.query) {\n\t\t\tconst queryString = qs.stringify(config.query, {\n\t\t\t\tencode: true,\n\t\t\t\tarrayFormat: 'brackets',\n\t\t\t\tskipNulls: true,\n\t\t\t});\n\t\t\tif (queryString) {\n\t\t\t\turl += `?${queryString}`;\n\t\t\t}\n\t\t}\n\n\t\t// Build request configuration\n\t\tlet requestConfig: RequestInit = {\n\t\t\tmethod: method.toUpperCase(),\n\t\t\theaders: {\n\t\t\t\t...this.defaultHeaders,\n\t\t\t\t...((config && 'headers' in config && config.headers) || {}),\n\t\t\t},\n\t\t};\n\n\t\t// Add body if present\n\t\tif (config && 'body' in config && config.body) {\n\t\t\trequestConfig.body = JSON.stringify(config.body);\n\t\t\trequestConfig.headers = {\n\t\t\t\t...requestConfig.headers,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t};\n\t\t}\n\n\t\t// Apply request interceptor\n\t\tif (this.options.onRequest) {\n\t\t\trequestConfig = await this.options.onRequest(requestConfig);\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request\n\t\t\tlet response = await this.fetchFn(`${this.baseURL}${url}`, requestConfig);\n\n\t\t\t// Apply response interceptor\n\t\t\tif (this.options.onResponse) {\n\t\t\t\tresponse = await this.options.onResponse(response);\n\t\t\t}\n\n\t\t\t// Handle errors\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow response;\n\t\t\t}\n\n\t\t\t// Handle empty responses (204 No Content, etc.)\n\t\t\tif (\n\t\t\t\tresponse.status === 204 ||\n\t\t\t\tresponse.headers.get('content-length') === '0'\n\t\t\t) {\n\t\t\t\treturn undefined as ExtractEndpointResponse<Paths, T>;\n\t\t\t}\n\n\t\t\t// Parse JSON response\n\t\t\tconst data = await response.json();\n\t\t\treturn data as ExtractEndpointResponse<Paths, T>;\n\t\t} catch (error) {\n\t\t\t// Apply error handler\n\t\t\tif (this.options.onError) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tawait this.options.onError(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\twrap<E = unknown>(onError?: ErrorTransformer<E>) {\n\t\treturn <T extends TypedEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t): Promise<WrappedResult<ExtractEndpointResponse<Paths, T>, E>> =>\n\t\t\tthis.request(endpoint, config).then(\n\t\t\t\t(data) => ({ ok: true as const, data }),\n\t\t\t\tasync (error) => ({\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: onError ? await onError(error) : (error as E),\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\tprivate parseEndpoint<T extends EndpointString>(\n\t\tendpoint: T,\n\t): ParseEndpoint<T> {\n\t\tconst [method, ...routeParts] = endpoint.split(' ');\n\t\tconst route = routeParts.join(' ');\n\t\treturn { method: method?.toLowerCase() ?? '', route } as ParseEndpoint<T>;\n\t}\n}\n\nexport function createTypedFetcher<Paths>(options?: FetcherOptions) {\n\tconst fetcher = new TypedFetcher<Paths>(options);\n\tconst fn = <T extends TypedEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => fetcher.request(endpoint, config);\n\n\treturn Object.assign(fn, {\n\t\twrap: <E = unknown>(onError?: ErrorTransformer<E>) =>\n\t\t\tObject.assign(fetcher.wrap(onError), fn, {\n\t\t\t\twrap: undefined,\n\t\t\t}),\n\t});\n}\n\nexport type FetchFn = typeof fetch;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,IAAa,eAAb,MAAa,aAAoB;CAChC;CACA;CACA;CACA;CAEA,OAAO,WAAW,IAAuB;EACxC,IAAI,IACH,OAAO;EAGR,IAAI,OAAO,WAAW,eAAe,OAAO,OAAO,UAAU,YAC5D,OAAO,OAAO,MAAM,KAAK,MAAM;EAGhC,IACC,OAAO,eAAe,eACtB,OAAO,WAAW,UAAU,YAE5B,OAAO,WAAW,MAAM,KAAK,UAAU;EAGxC,MAAM,IAAI,MAAM,+BAA+B;CAChD;CAEA,YAAY,UAA0B,CAAC,GAAG;EACzC,KAAK,UAAU,QAAQ,WAAW;EAClC,KAAK,iBAAiB,QAAQ,WAAW,CAAC;EAC1C,KAAK,UAAU;EACf,KAAK,UAAU,aAAa,WAAW,QAAQ,KAAK;CACrD;CAEA,MAAM,QACL,UACA,QAC6C;EAC7C,MAAM,EAAE,QAAQ,UAAU,KAAK,cAAc,QAAQ;EAGrD,IAAI,MAAM;EACV,IAAI,UAAU,YAAY,UAAU,OAAO,QAC1C,OAAO,QAAQ,OAAO,MAAiC,CAAC,CAAC,SACvD,CAAC,KAAK,WAAW;GACjB,MAAM,IAAI,QAAQ,IAAI,IAAI,IAAI,mBAAmB,OAAO,KAAK,CAAC,CAAC;EAChE,CACD;EAID,IAAI,UAAU,WAAW,UAAU,OAAO,OAAO;GAChD,MAAM,cAAc,GAAA,QAAG,UAAU,OAAO,OAAO;IAC9C,QAAQ;IACR,aAAa;IACb,WAAW;GACZ,CAAC;GACD,IAAI,aACH,OAAO,IAAI;EAEb;EAGA,IAAI,gBAA6B;GAChC,QAAQ,OAAO,YAAY;GAC3B,SAAS;IACR,GAAG,KAAK;IACR,GAAK,UAAU,aAAa,UAAU,OAAO,WAAY,CAAC;GAC3D;EACD;EAGA,IAAI,UAAU,UAAU,UAAU,OAAO,MAAM;GAC9C,cAAc,OAAO,KAAK,UAAU,OAAO,IAAI;GAC/C,cAAc,UAAU;IACvB,GAAG,cAAc;IACjB,gBAAgB;GACjB;EACD;EAGA,IAAI,KAAK,QAAQ,WAChB,gBAAgB,MAAM,KAAK,QAAQ,UAAU,aAAa;EAG3D,IAAI;GAEH,IAAI,WAAW,MAAM,KAAK,QAAQ,GAAG,KAAK,UAAU,OAAO,aAAa;GAGxE,IAAI,KAAK,QAAQ,YAChB,WAAW,MAAM,KAAK,QAAQ,WAAW,QAAQ;GAIlD,IAAI,CAAC,SAAS,IACb,MAAM;GAIP,IACC,SAAS,WAAW,OACpB,SAAS,QAAQ,IAAI,gBAAgB,MAAM,KAE3C;GAKD,OAAO,MADY,SAAS,KAAK;EAElC,SAAS,OAAO;GAEf,IAAI,KAAK,QAAQ,SAEhB,MAAM,KAAK,QAAQ,QAAQ,KAAK;GAEjC,MAAM;EACP;CACD;CAEA,KAAkB,SAA+B;EAChD,QACC,UACA,WAEA,KAAK,QAAQ,UAAU,MAAM,CAAC,CAAC,MAC7B,UAAU;GAAE,IAAI;GAAe;EAAK,IACrC,OAAO,WAAW;GACjB,IAAI;GACJ,OAAO,UAAU,MAAM,QAAQ,KAAK,IAAK;EAC1C,EACD;CACF;CAEA,cACC,UACmB;EACnB,MAAM,CAAC,QAAQ,GAAG,cAAc,SAAS,MAAM,GAAG;EAClD,MAAM,QAAQ,WAAW,KAAK,GAAG;EACjC,OAAO;GAAE,QAAQ,QAAQ,YAAY,KAAK;GAAI;EAAM;CACrD;AACD;AAEA,SAAgB,mBAA0B,SAA0B;CACnE,MAAM,UAAU,IAAI,aAAoB,OAAO;CAC/C,MAAM,MACL,UACA,WACI,QAAQ,QAAQ,UAAU,MAAM;CAErC,OAAO,OAAO,OAAO,IAAI,EACxB,OAAoB,YACnB,OAAO,OAAO,QAAQ,KAAK,OAAO,GAAG,IAAI,EACxC,MAAM,KAAA,EACP,CAAC,EACH,CAAC;AACF"}
|
package/dist/fetcher.d.cts
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
-
import { FetcherOptions, WrappedResult } from "./types
|
|
2
|
-
|
|
3
|
-
export
|
|
1
|
+
import { ErrorTransformer, ExtractEndpointResponse, FetcherOptions, FilteredRequestConfig, TypedEndpoint, WrappedResult } from "./types.cjs";
|
|
2
|
+
//#region src/fetcher.d.ts
|
|
3
|
+
export declare class TypedFetcher<Paths> {
|
|
4
|
+
private baseURL;
|
|
5
|
+
private defaultHeaders;
|
|
6
|
+
private options;
|
|
7
|
+
private fetchFn;
|
|
8
|
+
static getFetchFn(fn?: FetchFn): FetchFn;
|
|
9
|
+
constructor(options?: FetcherOptions);
|
|
10
|
+
request<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>): Promise<ExtractEndpointResponse<Paths, T>>;
|
|
11
|
+
wrap<E = unknown>(onError?: ErrorTransformer<E>): <T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>) => Promise<WrappedResult<ExtractEndpointResponse<Paths, T>, E>>;
|
|
12
|
+
private parseEndpoint;
|
|
13
|
+
}
|
|
14
|
+
export declare function createTypedFetcher<Paths>(options?: FetcherOptions): (<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>) => Promise<ExtractEndpointResponse<Paths, T>>) & {
|
|
15
|
+
wrap: <E = unknown>(onError?: ErrorTransformer<E>) => (<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T> | undefined) => Promise<WrappedResult<ExtractEndpointResponse<Paths, T>, E>>) & (<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>) => Promise<ExtractEndpointResponse<Paths, T>>) & {
|
|
16
|
+
wrap: undefined;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
export type FetchFn = typeof fetch;
|
|
20
|
+
//#endregion
|
|
21
|
+
export type { FetcherOptions, WrappedResult };
|
|
22
|
+
//# sourceMappingURL=fetcher.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetcher.d.cts","names":[],"sources":["../src/fetcher.ts"],"mappings":";;qBAca,aAAa;UACjB;UACA;UACA;UACA;SAED,WAAW,KAAK,UAAU;EAmBrB,YAAA,UAAS;EAOf,QAAQ,UAAU,cAAc,QACrC,UAAU,GACV,SAAS,sBAAsB,OAAO,KACpC,QAAQ,wBAAwB,OAAO;EAmF1C,KAAK,aAAa,UAAU,iBAAiB,MACpC,UAAU,cAAc,QAC/B,UAAU,GACV,SAAS,sBAAsB,OAAO,OACpC,QAAQ,cAAc,wBAAwB,OAAO,IAAI;UAUrD;;wBASO,mBAAmB,OAAO,UAAU,mBAEvC,UAAU,cAAc,QAAM,UAC/B,GAAC,SACF,sBAAsB,OAAO,OAAE,QAAA,wBAAA,OAAA;EAIjC,OAAA,aAAC,UAAsB,iBAAiB,SA9BvC,UAAC,cAAA,QAAA,UAAA,GAAA,SAAA,sBAAA,OAAA,mBAAA,QAAA,cAAA,wBAAA,OAAA,IAAA,SAwBE,UAAU,cAAc,QAAM,UAC/B,GAAC,SACF,sBAAsB,OAAO,OAAE,QAAA,wBAAA,OAAA;;;;YAW9B,iBAAiB"}
|
package/dist/fetcher.d.mts
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
-
import { FetcherOptions, WrappedResult } from "./types
|
|
2
|
-
|
|
3
|
-
export
|
|
1
|
+
import { ErrorTransformer, ExtractEndpointResponse, FetcherOptions, FilteredRequestConfig, TypedEndpoint, WrappedResult } from "./types.mjs";
|
|
2
|
+
//#region src/fetcher.d.ts
|
|
3
|
+
export declare class TypedFetcher<Paths> {
|
|
4
|
+
private baseURL;
|
|
5
|
+
private defaultHeaders;
|
|
6
|
+
private options;
|
|
7
|
+
private fetchFn;
|
|
8
|
+
static getFetchFn(fn?: FetchFn): FetchFn;
|
|
9
|
+
constructor(options?: FetcherOptions);
|
|
10
|
+
request<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>): Promise<ExtractEndpointResponse<Paths, T>>;
|
|
11
|
+
wrap<E = unknown>(onError?: ErrorTransformer<E>): <T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>) => Promise<WrappedResult<ExtractEndpointResponse<Paths, T>, E>>;
|
|
12
|
+
private parseEndpoint;
|
|
13
|
+
}
|
|
14
|
+
export declare function createTypedFetcher<Paths>(options?: FetcherOptions): (<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>) => Promise<ExtractEndpointResponse<Paths, T>>) & {
|
|
15
|
+
wrap: <E = unknown>(onError?: ErrorTransformer<E>) => (<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T> | undefined) => Promise<WrappedResult<ExtractEndpointResponse<Paths, T>, E>>) & (<T extends TypedEndpoint<Paths>>(endpoint: T, config?: FilteredRequestConfig<Paths, T>) => Promise<ExtractEndpointResponse<Paths, T>>) & {
|
|
16
|
+
wrap: undefined;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
export type FetchFn = typeof fetch;
|
|
20
|
+
//#endregion
|
|
21
|
+
export type { FetcherOptions, WrappedResult };
|
|
22
|
+
//# sourceMappingURL=fetcher.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetcher.d.mts","names":[],"sources":["../src/fetcher.ts"],"mappings":";;qBAca,aAAa;UACjB;UACA;UACA;UACA;SAED,WAAW,KAAK,UAAU;EAmBrB,YAAA,UAAS;EAOf,QAAQ,UAAU,cAAc,QACrC,UAAU,GACV,SAAS,sBAAsB,OAAO,KACpC,QAAQ,wBAAwB,OAAO;EAmF1C,KAAK,aAAa,UAAU,iBAAiB,MACpC,UAAU,cAAc,QAC/B,UAAU,GACV,SAAS,sBAAsB,OAAO,OACpC,QAAQ,cAAc,wBAAwB,OAAO,IAAI;UAUrD;;wBASO,mBAAmB,OAAO,UAAU,mBAEvC,UAAU,cAAc,QAAM,UAC/B,GAAC,SACF,sBAAsB,OAAO,OAAE,QAAA,wBAAA,OAAA;EAIjC,OAAA,aAAC,UAAsB,iBAAiB,SA9BvC,UAAC,cAAA,QAAA,UAAA,GAAA,SAAA,sBAAA,OAAA,mBAAA,QAAA,cAAA,wBAAA,OAAA,IAAA,SAwBE,UAAU,cAAc,QAAM,UAC/B,GAAC,SACF,sBAAsB,OAAO,OAAE,QAAA,wBAAA,OAAA;;;;YAW9B,iBAAiB"}
|
package/dist/fetcher.mjs
CHANGED
|
@@ -1,3 +1,86 @@
|
|
|
1
|
-
import
|
|
1
|
+
import qs from "qs";
|
|
2
|
+
//#region src/fetcher.ts
|
|
3
|
+
var TypedFetcher = class TypedFetcher {
|
|
4
|
+
baseURL;
|
|
5
|
+
defaultHeaders;
|
|
6
|
+
options;
|
|
7
|
+
fetchFn;
|
|
8
|
+
static getFetchFn(fn) {
|
|
9
|
+
if (fn) return fn;
|
|
10
|
+
if (typeof window !== "undefined" && typeof window.fetch === "function") return window.fetch.bind(window);
|
|
11
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.fetch === "function") return globalThis.fetch.bind(globalThis);
|
|
12
|
+
throw new Error("No fetch implementation found");
|
|
13
|
+
}
|
|
14
|
+
constructor(options = {}) {
|
|
15
|
+
this.baseURL = options.baseURL || "";
|
|
16
|
+
this.defaultHeaders = options.headers || {};
|
|
17
|
+
this.options = options;
|
|
18
|
+
this.fetchFn = TypedFetcher.getFetchFn(options.fetch);
|
|
19
|
+
}
|
|
20
|
+
async request(endpoint, config) {
|
|
21
|
+
const { method, route } = this.parseEndpoint(endpoint);
|
|
22
|
+
let url = route;
|
|
23
|
+
if (config && "params" in config && config.params) Object.entries(config.params).forEach(([key, value]) => {
|
|
24
|
+
url = url.replace(`{${key}}`, encodeURIComponent(String(value)));
|
|
25
|
+
});
|
|
26
|
+
if (config && "query" in config && config.query) {
|
|
27
|
+
const queryString = qs.stringify(config.query, {
|
|
28
|
+
encode: true,
|
|
29
|
+
arrayFormat: "brackets",
|
|
30
|
+
skipNulls: true
|
|
31
|
+
});
|
|
32
|
+
if (queryString) url += `?${queryString}`;
|
|
33
|
+
}
|
|
34
|
+
let requestConfig = {
|
|
35
|
+
method: method.toUpperCase(),
|
|
36
|
+
headers: {
|
|
37
|
+
...this.defaultHeaders,
|
|
38
|
+
...config && "headers" in config && config.headers || {}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
if (config && "body" in config && config.body) {
|
|
42
|
+
requestConfig.body = JSON.stringify(config.body);
|
|
43
|
+
requestConfig.headers = {
|
|
44
|
+
...requestConfig.headers,
|
|
45
|
+
"Content-Type": "application/json"
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (this.options.onRequest) requestConfig = await this.options.onRequest(requestConfig);
|
|
49
|
+
try {
|
|
50
|
+
let response = await this.fetchFn(`${this.baseURL}${url}`, requestConfig);
|
|
51
|
+
if (this.options.onResponse) response = await this.options.onResponse(response);
|
|
52
|
+
if (!response.ok) throw response;
|
|
53
|
+
if (response.status === 204 || response.headers.get("content-length") === "0") return;
|
|
54
|
+
return await response.json();
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (this.options.onError) await this.options.onError(error);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
wrap(onError) {
|
|
61
|
+
return (endpoint, config) => this.request(endpoint, config).then((data) => ({
|
|
62
|
+
ok: true,
|
|
63
|
+
data
|
|
64
|
+
}), async (error) => ({
|
|
65
|
+
ok: false,
|
|
66
|
+
error: onError ? await onError(error) : error
|
|
67
|
+
}));
|
|
68
|
+
}
|
|
69
|
+
parseEndpoint(endpoint) {
|
|
70
|
+
const [method, ...routeParts] = endpoint.split(" ");
|
|
71
|
+
const route = routeParts.join(" ");
|
|
72
|
+
return {
|
|
73
|
+
method: method?.toLowerCase() ?? "",
|
|
74
|
+
route
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
function createTypedFetcher(options) {
|
|
79
|
+
const fetcher = new TypedFetcher(options);
|
|
80
|
+
const fn = (endpoint, config) => fetcher.request(endpoint, config);
|
|
81
|
+
return Object.assign(fn, { wrap: (onError) => Object.assign(fetcher.wrap(onError), fn, { wrap: void 0 }) });
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
export { TypedFetcher, createTypedFetcher };
|
|
2
85
|
|
|
3
|
-
|
|
86
|
+
//# sourceMappingURL=fetcher.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetcher.mjs","names":[],"sources":["../src/fetcher.ts"],"sourcesContent":["import qs from 'qs';\nimport type {\n\tEndpointString,\n\tErrorTransformer,\n\tExtractEndpointResponse,\n\tFetcherOptions,\n\tFilteredRequestConfig,\n\tParseEndpoint,\n\tTypedEndpoint,\n\tWrappedResult,\n} from './types';\n\nexport type { FetcherOptions, WrappedResult } from './types';\n\nexport class TypedFetcher<Paths> {\n\tprivate baseURL: string;\n\tprivate defaultHeaders: Record<string, string>;\n\tprivate options: FetcherOptions;\n\tprivate fetchFn: FetchFn;\n\n\tstatic getFetchFn(fn?: FetchFn): FetchFn {\n\t\tif (fn) {\n\t\t\treturn fn;\n\t\t}\n\n\t\tif (typeof window !== 'undefined' && typeof window.fetch === 'function') {\n\t\t\treturn window.fetch.bind(window);\n\t\t}\n\n\t\tif (\n\t\t\ttypeof globalThis !== 'undefined' &&\n\t\t\ttypeof globalThis.fetch === 'function'\n\t\t) {\n\t\t\treturn globalThis.fetch.bind(globalThis);\n\t\t}\n\n\t\tthrow new Error('No fetch implementation found');\n\t}\n\n\tconstructor(options: FetcherOptions = {}) {\n\t\tthis.baseURL = options.baseURL || '';\n\t\tthis.defaultHeaders = options.headers || {};\n\t\tthis.options = options;\n\t\tthis.fetchFn = TypedFetcher.getFetchFn(options.fetch);\n\t}\n\n\tasync request<T extends TypedEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t): Promise<ExtractEndpointResponse<Paths, T>> {\n\t\tconst { method, route } = this.parseEndpoint(endpoint);\n\n\t\t// Replace path parameters\n\t\tlet url = route;\n\t\tif (config && 'params' in config && config.params) {\n\t\t\tObject.entries(config.params as Record<string, unknown>).forEach(\n\t\t\t\t([key, value]) => {\n\t\t\t\t\turl = url.replace(`{${key}}`, encodeURIComponent(String(value)));\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\t// Add query parameters\n\t\tif (config && 'query' in config && config.query) {\n\t\t\tconst queryString = qs.stringify(config.query, {\n\t\t\t\tencode: true,\n\t\t\t\tarrayFormat: 'brackets',\n\t\t\t\tskipNulls: true,\n\t\t\t});\n\t\t\tif (queryString) {\n\t\t\t\turl += `?${queryString}`;\n\t\t\t}\n\t\t}\n\n\t\t// Build request configuration\n\t\tlet requestConfig: RequestInit = {\n\t\t\tmethod: method.toUpperCase(),\n\t\t\theaders: {\n\t\t\t\t...this.defaultHeaders,\n\t\t\t\t...((config && 'headers' in config && config.headers) || {}),\n\t\t\t},\n\t\t};\n\n\t\t// Add body if present\n\t\tif (config && 'body' in config && config.body) {\n\t\t\trequestConfig.body = JSON.stringify(config.body);\n\t\t\trequestConfig.headers = {\n\t\t\t\t...requestConfig.headers,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t};\n\t\t}\n\n\t\t// Apply request interceptor\n\t\tif (this.options.onRequest) {\n\t\t\trequestConfig = await this.options.onRequest(requestConfig);\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request\n\t\t\tlet response = await this.fetchFn(`${this.baseURL}${url}`, requestConfig);\n\n\t\t\t// Apply response interceptor\n\t\t\tif (this.options.onResponse) {\n\t\t\t\tresponse = await this.options.onResponse(response);\n\t\t\t}\n\n\t\t\t// Handle errors\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow response;\n\t\t\t}\n\n\t\t\t// Handle empty responses (204 No Content, etc.)\n\t\t\tif (\n\t\t\t\tresponse.status === 204 ||\n\t\t\t\tresponse.headers.get('content-length') === '0'\n\t\t\t) {\n\t\t\t\treturn undefined as ExtractEndpointResponse<Paths, T>;\n\t\t\t}\n\n\t\t\t// Parse JSON response\n\t\t\tconst data = await response.json();\n\t\t\treturn data as ExtractEndpointResponse<Paths, T>;\n\t\t} catch (error) {\n\t\t\t// Apply error handler\n\t\t\tif (this.options.onError) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tawait this.options.onError(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\twrap<E = unknown>(onError?: ErrorTransformer<E>) {\n\t\treturn <T extends TypedEndpoint<Paths>>(\n\t\t\tendpoint: T,\n\t\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t\t): Promise<WrappedResult<ExtractEndpointResponse<Paths, T>, E>> =>\n\t\t\tthis.request(endpoint, config).then(\n\t\t\t\t(data) => ({ ok: true as const, data }),\n\t\t\t\tasync (error) => ({\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: onError ? await onError(error) : (error as E),\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\tprivate parseEndpoint<T extends EndpointString>(\n\t\tendpoint: T,\n\t): ParseEndpoint<T> {\n\t\tconst [method, ...routeParts] = endpoint.split(' ');\n\t\tconst route = routeParts.join(' ');\n\t\treturn { method: method?.toLowerCase() ?? '', route } as ParseEndpoint<T>;\n\t}\n}\n\nexport function createTypedFetcher<Paths>(options?: FetcherOptions) {\n\tconst fetcher = new TypedFetcher<Paths>(options);\n\tconst fn = <T extends TypedEndpoint<Paths>>(\n\t\tendpoint: T,\n\t\tconfig?: FilteredRequestConfig<Paths, T>,\n\t) => fetcher.request(endpoint, config);\n\n\treturn Object.assign(fn, {\n\t\twrap: <E = unknown>(onError?: ErrorTransformer<E>) =>\n\t\t\tObject.assign(fetcher.wrap(onError), fn, {\n\t\t\t\twrap: undefined,\n\t\t\t}),\n\t});\n}\n\nexport type FetchFn = typeof fetch;\n"],"mappings":";;AAcA,IAAa,eAAb,MAAa,aAAoB;CAChC;CACA;CACA;CACA;CAEA,OAAO,WAAW,IAAuB;EACxC,IAAI,IACH,OAAO;EAGR,IAAI,OAAO,WAAW,eAAe,OAAO,OAAO,UAAU,YAC5D,OAAO,OAAO,MAAM,KAAK,MAAM;EAGhC,IACC,OAAO,eAAe,eACtB,OAAO,WAAW,UAAU,YAE5B,OAAO,WAAW,MAAM,KAAK,UAAU;EAGxC,MAAM,IAAI,MAAM,+BAA+B;CAChD;CAEA,YAAY,UAA0B,CAAC,GAAG;EACzC,KAAK,UAAU,QAAQ,WAAW;EAClC,KAAK,iBAAiB,QAAQ,WAAW,CAAC;EAC1C,KAAK,UAAU;EACf,KAAK,UAAU,aAAa,WAAW,QAAQ,KAAK;CACrD;CAEA,MAAM,QACL,UACA,QAC6C;EAC7C,MAAM,EAAE,QAAQ,UAAU,KAAK,cAAc,QAAQ;EAGrD,IAAI,MAAM;EACV,IAAI,UAAU,YAAY,UAAU,OAAO,QAC1C,OAAO,QAAQ,OAAO,MAAiC,CAAC,CAAC,SACvD,CAAC,KAAK,WAAW;GACjB,MAAM,IAAI,QAAQ,IAAI,IAAI,IAAI,mBAAmB,OAAO,KAAK,CAAC,CAAC;EAChE,CACD;EAID,IAAI,UAAU,WAAW,UAAU,OAAO,OAAO;GAChD,MAAM,cAAc,GAAG,UAAU,OAAO,OAAO;IAC9C,QAAQ;IACR,aAAa;IACb,WAAW;GACZ,CAAC;GACD,IAAI,aACH,OAAO,IAAI;EAEb;EAGA,IAAI,gBAA6B;GAChC,QAAQ,OAAO,YAAY;GAC3B,SAAS;IACR,GAAG,KAAK;IACR,GAAK,UAAU,aAAa,UAAU,OAAO,WAAY,CAAC;GAC3D;EACD;EAGA,IAAI,UAAU,UAAU,UAAU,OAAO,MAAM;GAC9C,cAAc,OAAO,KAAK,UAAU,OAAO,IAAI;GAC/C,cAAc,UAAU;IACvB,GAAG,cAAc;IACjB,gBAAgB;GACjB;EACD;EAGA,IAAI,KAAK,QAAQ,WAChB,gBAAgB,MAAM,KAAK,QAAQ,UAAU,aAAa;EAG3D,IAAI;GAEH,IAAI,WAAW,MAAM,KAAK,QAAQ,GAAG,KAAK,UAAU,OAAO,aAAa;GAGxE,IAAI,KAAK,QAAQ,YAChB,WAAW,MAAM,KAAK,QAAQ,WAAW,QAAQ;GAIlD,IAAI,CAAC,SAAS,IACb,MAAM;GAIP,IACC,SAAS,WAAW,OACpB,SAAS,QAAQ,IAAI,gBAAgB,MAAM,KAE3C;GAKD,OAAO,MADY,SAAS,KAAK;EAElC,SAAS,OAAO;GAEf,IAAI,KAAK,QAAQ,SAEhB,MAAM,KAAK,QAAQ,QAAQ,KAAK;GAEjC,MAAM;EACP;CACD;CAEA,KAAkB,SAA+B;EAChD,QACC,UACA,WAEA,KAAK,QAAQ,UAAU,MAAM,CAAC,CAAC,MAC7B,UAAU;GAAE,IAAI;GAAe;EAAK,IACrC,OAAO,WAAW;GACjB,IAAI;GACJ,OAAO,UAAU,MAAM,QAAQ,KAAK,IAAK;EAC1C,EACD;CACF;CAEA,cACC,UACmB;EACnB,MAAM,CAAC,QAAQ,GAAG,cAAc,SAAS,MAAM,GAAG;EAClD,MAAM,QAAQ,WAAW,KAAK,GAAG;EACjC,OAAO;GAAE,QAAQ,QAAQ,YAAY,KAAK;GAAI;EAAM;CACrD;AACD;AAEA,SAAgB,mBAA0B,SAA0B;CACnE,MAAM,UAAU,IAAI,aAAoB,OAAO;CAC/C,MAAM,MACL,UACA,WACI,QAAQ,QAAQ,UAAU,MAAM;CAErC,OAAO,OAAO,OAAO,IAAI,EACxB,OAAoB,YACnB,OAAO,OAAO,QAAQ,KAAK,OAAO,GAAG,IAAI,EACxC,MAAM,KAAA,EACP,CAAC,EACH,CAAC;AACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
const
|
|
3
|
-
require(
|
|
4
|
-
require(
|
|
5
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_fetcher = require("./fetcher.cjs");
|
|
3
|
+
const require_auth_fetcher = require("./auth-fetcher.cjs");
|
|
4
|
+
require("./infer.cjs");
|
|
5
|
+
require("./types.cjs");
|
|
6
6
|
exports.TypedFetcher = require_fetcher.TypedFetcher;
|
|
7
7
|
exports.createAuthAwareFetcher = require_auth_fetcher.createAuthAwareFetcher;
|
|
8
|
-
exports.createTypedFetcher = require_fetcher.createTypedFetcher;
|
|
8
|
+
exports.createTypedFetcher = require_fetcher.createTypedFetcher;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { EndpointString, ErrorTransformer, ExtractEndpointConfig, ExtractEndpointResponse, ExtractMethod, ExtractPathParams, ExtractQueryParams, ExtractRequestBody, ExtractResponse, FetcherOptions, FilterEndpointByMethod, FilteredRequestConfig, IsConfigRequired, MutationEndpoint, OpenAPIRoutes, ParseEndpoint, QueryEndpoint, RequestConfig, TypedApiFunction, TypedEndpoint, ValidEndpoint, WrappedApiFunction, WrappedResult } from "./types
|
|
2
|
-
import { ApiKeyProvider, AuthFetcherOptions, AuthStrategy, AuthenticatedEndpoints, AwsSigner, GetEndpointAuth, PublicEndpoints, SecuritySchemeObject, TokenProvider, UsedSecuritySchemes, createAuthAwareFetcher } from "./auth-fetcher
|
|
3
|
-
import { FetchFn, TypedFetcher, createTypedFetcher } from "./fetcher
|
|
4
|
-
import { InferOpenApi, InferOpenApiFromEndpoint } from "./infer
|
|
1
|
+
import { EndpointString, ErrorTransformer, ExtractEndpointConfig, ExtractEndpointResponse, ExtractMethod, ExtractPathParams, ExtractQueryParams, ExtractRequestBody, ExtractResponse, FetcherOptions, FilterEndpointByMethod, FilteredRequestConfig, IsConfigRequired, MutationEndpoint, OpenAPIRoutes, ParseEndpoint, QueryEndpoint, RequestConfig, TypedApiFunction, TypedEndpoint, ValidEndpoint, WrappedApiFunction, WrappedResult } from "./types.cjs";
|
|
2
|
+
import { ApiKeyProvider, AuthFetcherOptions, AuthStrategy, AuthenticatedEndpoints, AwsSigner, GetEndpointAuth, PublicEndpoints, SecuritySchemeObject, TokenProvider, UsedSecuritySchemes, createAuthAwareFetcher } from "./auth-fetcher.cjs";
|
|
3
|
+
import { FetchFn, TypedFetcher, createTypedFetcher } from "./fetcher.cjs";
|
|
4
|
+
import { InferOpenApi, InferOpenApiFromEndpoint } from "./infer.cjs";
|
|
5
5
|
export { ApiKeyProvider, AuthFetcherOptions, AuthStrategy, AuthenticatedEndpoints, AwsSigner, EndpointString, ErrorTransformer, ExtractEndpointConfig, ExtractEndpointResponse, ExtractMethod, ExtractPathParams, ExtractQueryParams, ExtractRequestBody, ExtractResponse, FetchFn, FetcherOptions, FilterEndpointByMethod, FilteredRequestConfig, GetEndpointAuth, InferOpenApi, InferOpenApiFromEndpoint, IsConfigRequired, MutationEndpoint, OpenAPIRoutes, ParseEndpoint, PublicEndpoints, QueryEndpoint, RequestConfig, SecuritySchemeObject, TokenProvider, TypedApiFunction, TypedEndpoint, TypedFetcher, UsedSecuritySchemes, ValidEndpoint, WrappedApiFunction, WrappedResult, createAuthAwareFetcher, createTypedFetcher };
|