@openapi-qraft/react 2.0.0-next.9 → 2.0.1-beta.0
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/CHANGELOG.md +149 -0
- package/dist/cjs/callbacks/ensureInfiniteQueryData.cjs +10 -0
- package/dist/cjs/callbacks/ensureInfiniteQueryData.cjs.map +1 -0
- package/dist/cjs/callbacks/ensureQueryData.cjs +10 -0
- package/dist/cjs/callbacks/ensureQueryData.cjs.map +1 -0
- package/dist/cjs/callbacks/index.cjs +4 -0
- package/dist/cjs/callbacks/index.cjs.map +1 -1
- package/dist/cjs/lib/callQueryClientFetchMethod.cjs.map +1 -1
- package/dist/cjs/lib/requestFn.cjs +67 -64
- package/dist/cjs/lib/requestFn.cjs.map +1 -1
- package/dist/cjs/lib/responseUtils.cjs +41 -0
- package/dist/cjs/lib/responseUtils.cjs.map +1 -0
- package/dist/cjs/qraftAPIClient.cjs +2 -2
- package/dist/cjs/qraftAPIClient.cjs.map +1 -1
- package/dist/cjs/unstable__responseUtils.cjs +9 -0
- package/dist/cjs/unstable__responseUtils.cjs.map +1 -0
- package/dist/esm/callbacks/ensureInfiniteQueryData.js +8 -0
- package/dist/esm/callbacks/ensureInfiniteQueryData.js.map +1 -0
- package/dist/esm/callbacks/ensureQueryData.js +8 -0
- package/dist/esm/callbacks/ensureQueryData.js.map +1 -0
- package/dist/esm/callbacks/index.js +2 -0
- package/dist/esm/callbacks/index.js.map +1 -1
- package/dist/esm/lib/callQueryClientFetchMethod.js.map +1 -1
- package/dist/esm/lib/requestFn.js +66 -63
- package/dist/esm/lib/requestFn.js.map +1 -1
- package/dist/esm/lib/responseUtils.js +38 -0
- package/dist/esm/lib/responseUtils.js.map +1 -0
- package/dist/esm/qraftAPIClient.js +2 -2
- package/dist/esm/qraftAPIClient.js.map +1 -1
- package/dist/esm/unstable__responseUtils.js +2 -0
- package/dist/esm/unstable__responseUtils.js.map +1 -0
- package/dist/types/callbacks/ensureInfiniteQueryData.d.ts +8 -0
- package/dist/types/callbacks/ensureInfiniteQueryData.d.ts.map +1 -0
- package/dist/types/callbacks/ensureQueryData.d.ts +8 -0
- package/dist/types/callbacks/ensureQueryData.d.ts.map +1 -0
- package/dist/types/callbacks/index.d.ts +2 -0
- package/dist/types/callbacks/index.d.ts.map +1 -1
- package/dist/types/lib/callQueryClientFetchMethod.d.ts +1 -1
- package/dist/types/lib/callQueryClientFetchMethod.d.ts.map +1 -1
- package/dist/types/lib/requestFn.d.ts +17 -2
- package/dist/types/lib/requestFn.d.ts.map +1 -1
- package/dist/types/lib/responseUtils.d.ts +13 -0
- package/dist/types/lib/responseUtils.d.ts.map +1 -0
- package/dist/types/qraftAPIClient.d.ts +1 -1
- package/dist/types/qraftAPIClient.d.ts.map +1 -1
- package/dist/types/unstable__responseUtils.d.ts +2 -0
- package/dist/types/unstable__responseUtils.d.ts.map +1 -0
- package/package.json +16 -11
- package/src/callbacks/ensureInfiniteQueryData.ts +29 -0
- package/src/callbacks/ensureQueryData.ts +29 -0
- package/src/callbacks/index.ts +2 -0
- package/src/lib/callQueryClientFetchMethod.ts +3 -1
- package/src/lib/requestFn.ts +92 -115
- package/src/lib/responseUtils.ts +74 -0
- package/src/qraftAPIClient.ts +5 -2
- package/src/unstable__responseUtils.ts +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,154 @@
|
|
|
1
1
|
# @openapi-qraft/react
|
|
2
2
|
|
|
3
|
+
## 2.0.1-beta.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.1-beta.0
|
|
8
|
+
|
|
9
|
+
## 2.0.0
|
|
10
|
+
|
|
11
|
+
### Major Changes
|
|
12
|
+
|
|
13
|
+
- 5b64278: Refactored service method generation in **OpenAPI Qraft v2** with improved DX, including full TSDoc support and optimized autocomplete performance.
|
|
14
|
+
- caff377: Removed the option to pass a `QueryClient` for hooks or methods.
|
|
15
|
+
|
|
16
|
+
**Details**:
|
|
17
|
+
This decision was made to streamline the developer experience and to reduce the potential for errors.
|
|
18
|
+
|
|
19
|
+
- The `QueryClient` is no longer needed for methods like `qraft.<service>.<operation>.getQueryData(...)` and has been
|
|
20
|
+
removed entirely.
|
|
21
|
+
This change was made to simplify the API and avoid potential confusion.
|
|
22
|
+
- The ability to pass an optional `QueryClient` for hooks has been removed.
|
|
23
|
+
- Now, there is only one `QueryClient` instance associated with the `createAPIClient`.
|
|
24
|
+
This ensures consistent data management throughout the project.
|
|
25
|
+
|
|
26
|
+
**Impact**:
|
|
27
|
+
|
|
28
|
+
- All hooks or methods that previously accepted an optional/required `QueryClient` should now rely on the single,
|
|
29
|
+
consistent `QueryClient` associated with the `createAPIClient`.
|
|
30
|
+
|
|
31
|
+
- 2b0fb30: Return `{ data, error, response }` from `requestFn` Instead of `Promise.reject(error)`
|
|
32
|
+
|
|
33
|
+
This change promotes stricter error handling within the application.
|
|
34
|
+
|
|
35
|
+
- 266611a: Enhance `createAPIClient` to accept `requestFn`, `baseUrl`, and optionally `queryClient`.
|
|
36
|
+
- 0aca269: Removed `QraftContext` in favor of enhanced functionality in `createAPIClient(...)`.
|
|
37
|
+
|
|
38
|
+
### Minor Changes
|
|
39
|
+
|
|
40
|
+
- 56687f3: Added support for calling `qraftAPIClient(...)` with `{ queryClient }`, enabling non-fetching actions like `resetQueries()`.
|
|
41
|
+
- 8bbe14b: Added two new utility functions: `ensureQueryData` and `ensureInfiniteQueryData`. These methods improve data fetching workflows by allowing seamless retrieval of cached data or fetching it when unavailable. `ensureQueryData` supports standard queries, while `ensureInfiniteQueryData` is tailored for infinite queries, including paginated data handling.
|
|
42
|
+
- 0b3cda1: Updated the `qraftAPIClient(...)` to return only the set of services corresponding to the methods for which callbacks were passed.
|
|
43
|
+
- 76634bf: ### Changeset: `createPredefinedParametersRequestFn`
|
|
44
|
+
|
|
45
|
+
Introduced `createPredefinedParametersRequestFn`, generated by the `@openapi-qraft/cli` using
|
|
46
|
+
the `--operation-predefined-parameters` option.
|
|
47
|
+
This function allows for the automatic application of predefined
|
|
48
|
+
parameters to selected API operations by wrapping the base `requestFn`. It simplifies managing parameters, reducing
|
|
49
|
+
boilerplate code, and supports both static and dynamic values, enhancing flexibility in API request handling.
|
|
50
|
+
|
|
51
|
+
- a50253a: Responses with the `text/plain` content type are now always processed as plain text, without attempting to fallback to `JSON.parse`.
|
|
52
|
+
- 2099907: Enhanced usage of `parameters`
|
|
53
|
+
in `getQueryData(...)`, `getInfiniteQueryData(...)`, `getMutationData(...)`, `getQueryKey(...)`,
|
|
54
|
+
and `getInfiniteQueryKey(...)`. Now, when not all query parameters are optional (according to OpenAPI), the parameters
|
|
55
|
+
can be omitted as the first argument.
|
|
56
|
+
|
|
57
|
+
### Patch Changes
|
|
58
|
+
|
|
59
|
+
- 4ef9ce0: Clarified `FetchInfiniteQueryOptions` type to align with the latest TanStack Query version (5.56.2).
|
|
60
|
+
- 057292f: Removed deprecated `mutationFn` and `queryFn` methods.
|
|
61
|
+
- 5b864e5: Improved parameter types for `useSuspenseInfiniteQuery(...)` and `useSuspenseQuery(...)`.
|
|
62
|
+
- 9dc1918: Simplified `TParams` type for conditional expressions.
|
|
63
|
+
- aff34d8: Made `RequestFnResponse` type more strict.
|
|
64
|
+
- 78638a5: Extended TSDoc generation for existing `useQuery`, `useMutation`, `useInfiniteQuery`, `useIsFetching` and `useIsMutating` hooks, now including detailed usage examples.
|
|
65
|
+
- 665a77d: Add `ensureQueryData` methods to `QueryOperationCallbacks`.
|
|
66
|
+
- 56191e1: Updated the `getQueryState(...)` function to support being invoked without parameters if they are not required. This enhancement simplifies the usage in scenarios where the parameters are optional, providing a more flexible API.
|
|
67
|
+
- 7e51026: Added the ability to call `getQueryKey`, `getMutationKey`, and similar non-request operations without providing `requestFn` or `baseUrl`
|
|
68
|
+
- bbcac65: Refined all types related to value in the `qraftPredefinedParametersRequestFn(...)` function.
|
|
69
|
+
- 3ed94dc: Implemented support for requests with multiple media types. Now, if an endpoint accepts more than one media type (e.g., JSON and form-data), types will be generated to account for all possible cases, ensuring compatibility with both JSON and form-data input formats.
|
|
70
|
+
- 1168760: Marked `RequestFnPayload` as deprecated in favor of `RequestFnInfo` for a more descriptive and consistent API.
|
|
71
|
+
- cfe7d0a: `createAPIClient` now allows calling `getInfiniteQueryKey()` without requiring `queryClient` in options.
|
|
72
|
+
- d804cb6: Added missing dist file for `qraftPredefinedParametersRequestFn`.
|
|
73
|
+
- Updated dependencies [8bbe14b]
|
|
74
|
+
- Updated dependencies [3ed94dc]
|
|
75
|
+
- Updated dependencies [34ff132]
|
|
76
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0
|
|
77
|
+
|
|
78
|
+
## 2.0.0-next.19
|
|
79
|
+
|
|
80
|
+
### Patch Changes
|
|
81
|
+
|
|
82
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.19
|
|
83
|
+
|
|
84
|
+
## 2.0.0-next.18
|
|
85
|
+
|
|
86
|
+
### Patch Changes
|
|
87
|
+
|
|
88
|
+
- 665a77d: Add `ensureQueryData` methods to `QueryOperationCallbacks`.
|
|
89
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.18
|
|
90
|
+
|
|
91
|
+
## 2.0.0-next.17
|
|
92
|
+
|
|
93
|
+
### Minor Changes
|
|
94
|
+
|
|
95
|
+
- 8bbe14b: Added two new utility functions: `ensureQueryData` and `ensureInfiniteQueryData`. These methods improve data fetching workflows by allowing seamless retrieval of cached data or fetching it when unavailable. `ensureQueryData` supports standard queries, while `ensureInfiniteQueryData` is tailored for infinite queries, including paginated data handling.
|
|
96
|
+
|
|
97
|
+
### Patch Changes
|
|
98
|
+
|
|
99
|
+
- Updated dependencies [8bbe14b]
|
|
100
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.17
|
|
101
|
+
|
|
102
|
+
## 2.0.0-next.16
|
|
103
|
+
|
|
104
|
+
### Patch Changes
|
|
105
|
+
|
|
106
|
+
- cfe7d0a: `createAPIClient` now allows calling `getInfiniteQueryKey()` without requiring `queryClient` in options.
|
|
107
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.16
|
|
108
|
+
|
|
109
|
+
## 2.0.0-next.15
|
|
110
|
+
|
|
111
|
+
### Patch Changes
|
|
112
|
+
|
|
113
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.15
|
|
114
|
+
|
|
115
|
+
## 2.0.0-next.14
|
|
116
|
+
|
|
117
|
+
### Patch Changes
|
|
118
|
+
|
|
119
|
+
- Updated dependencies [34ff132]
|
|
120
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.14
|
|
121
|
+
|
|
122
|
+
## 2.0.0-next.13
|
|
123
|
+
|
|
124
|
+
### Patch Changes
|
|
125
|
+
|
|
126
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.13
|
|
127
|
+
|
|
128
|
+
## 2.0.0-next.12
|
|
129
|
+
|
|
130
|
+
### Minor Changes
|
|
131
|
+
|
|
132
|
+
- a50253a: Responses with the `text/plain` content type are now always processed as plain text, without attempting to fallback to `JSON.parse`.
|
|
133
|
+
|
|
134
|
+
### Patch Changes
|
|
135
|
+
|
|
136
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.12
|
|
137
|
+
|
|
138
|
+
## 2.0.0-next.11
|
|
139
|
+
|
|
140
|
+
### Patch Changes
|
|
141
|
+
|
|
142
|
+
- 3ed94dc: Implemented support for requests with multiple media types. Now, if an endpoint accepts more than one media type (e.g., JSON and form-data), types will be generated to account for all possible cases, ensuring compatibility with both JSON and form-data input formats.
|
|
143
|
+
- Updated dependencies [3ed94dc]
|
|
144
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.11
|
|
145
|
+
|
|
146
|
+
## 2.0.0-next.10
|
|
147
|
+
|
|
148
|
+
### Patch Changes
|
|
149
|
+
|
|
150
|
+
- @openapi-qraft/tanstack-query-react-types@2.0.0-next.10
|
|
151
|
+
|
|
3
152
|
## 2.0.0-next.9
|
|
4
153
|
|
|
5
154
|
### Patch Changes
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var callQueryClientFetchMethod = require('../lib/callQueryClientFetchMethod.cjs');
|
|
4
|
+
|
|
5
|
+
const ensureInfiniteQueryData = (qraftOptions, schema, args)=>{
|
|
6
|
+
return callQueryClientFetchMethod.callQueryClientMethodWithQueryKey(qraftOptions, 'ensureInfiniteQueryData', schema, true, args);
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
exports.ensureInfiniteQueryData = ensureInfiniteQueryData;
|
|
10
|
+
//# sourceMappingURL=ensureInfiniteQueryData.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ensureInfiniteQueryData.cjs","sources":["../../../src/callbacks/ensureInfiniteQueryData.ts"],"sourcesContent":["import type { ServiceOperationFetchInfiniteQuery } from '@openapi-qraft/tanstack-query-react-types';\nimport type { DefaultError } from '@tanstack/query-core';\nimport type { CreateAPIQueryClientOptions } from '../qraftAPIClient.js';\nimport { callQueryClientMethodWithQueryKey } from '../lib/callQueryClientFetchMethod.js';\n\nexport const ensureInfiniteQueryData: <\n TSchema extends { url: string; method: 'get' | 'head' | 'options' },\n TData,\n TParams,\n>(\n qraftOptions: CreateAPIQueryClientOptions,\n schema: TSchema,\n args: Parameters<\n ServiceOperationFetchInfiniteQuery<\n TSchema,\n TData,\n TParams,\n DefaultError\n >['ensureInfiniteQueryData']\n >\n) => Promise<TData> = (qraftOptions, schema, args) => {\n return callQueryClientMethodWithQueryKey(\n qraftOptions,\n 'ensureInfiniteQueryData',\n schema,\n true,\n args as never\n ) as never;\n};\n"],"names":["ensureInfiniteQueryData","qraftOptions","schema","args","callQueryClientMethodWithQueryKey"],"mappings":";;;;AAKaA,MAAAA,uBAAAA,GAeS,CAACC,YAAAA,EAAcC,MAAQC,EAAAA,IAAAA,GAAAA;AAC3C,IAAA,OAAOC,4DACLH,CAAAA,YAAAA,EACA,yBACAC,EAAAA,MAAAA,EACA,IACAC,EAAAA,IAAAA,CAAAA,CAAAA;AAEJ;;;;"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var callQueryClientFetchMethod = require('../lib/callQueryClientFetchMethod.cjs');
|
|
4
|
+
|
|
5
|
+
const ensureQueryData = (qraftOptions, schema, args)=>{
|
|
6
|
+
return callQueryClientFetchMethod.callQueryClientMethodWithQueryKey(qraftOptions, 'ensureQueryData', schema, false, args);
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
exports.ensureQueryData = ensureQueryData;
|
|
10
|
+
//# sourceMappingURL=ensureQueryData.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ensureQueryData.cjs","sources":["../../../src/callbacks/ensureQueryData.ts"],"sourcesContent":["import type { ServiceOperationFetchQuery } from '@openapi-qraft/tanstack-query-react-types';\nimport type { DefaultError } from '@tanstack/query-core';\nimport type { CreateAPIQueryClientOptions } from '../qraftAPIClient.js';\nimport { callQueryClientMethodWithQueryKey } from '../lib/callQueryClientFetchMethod.js';\n\nexport const ensureQueryData: <\n TSchema extends { url: string; method: 'get' | 'head' | 'options' },\n TData,\n TParams,\n>(\n qraftOptions: CreateAPIQueryClientOptions,\n schema: TSchema,\n args: Parameters<\n ServiceOperationFetchQuery<\n TSchema,\n TData,\n TParams,\n DefaultError\n >['ensureQueryData']\n >\n) => Promise<TData> = (qraftOptions, schema, args) => {\n return callQueryClientMethodWithQueryKey(\n qraftOptions,\n 'ensureQueryData',\n schema,\n false,\n args as never\n ) as never;\n};\n"],"names":["ensureQueryData","qraftOptions","schema","args","callQueryClientMethodWithQueryKey"],"mappings":";;;;AAKaA,MAAAA,eAAAA,GAeS,CAACC,YAAAA,EAAcC,MAAQC,EAAAA,IAAAA,GAAAA;AAC3C,IAAA,OAAOC,4DACLH,CAAAA,YAAAA,EACA,iBACAC,EAAAA,MAAAA,EACA,KACAC,EAAAA,IAAAA,CAAAA,CAAAA;AAEJ;;;;"}
|
|
@@ -28,8 +28,10 @@ var isMutating = require('./isMutating.cjs');
|
|
|
28
28
|
var useIsFetching = require('./useIsFetching.cjs');
|
|
29
29
|
var fetchQuery = require('./fetchQuery.cjs');
|
|
30
30
|
var prefetchQuery = require('./prefetchQuery.cjs');
|
|
31
|
+
var ensureQueryData = require('./ensureQueryData.cjs');
|
|
31
32
|
var fetchInfiniteQuery = require('./fetchInfiniteQuery.cjs');
|
|
32
33
|
var prefetchInfiniteQuery = require('./prefetchInfiniteQuery.cjs');
|
|
34
|
+
var ensureInfiniteQueryData = require('./ensureInfiniteQueryData.cjs');
|
|
33
35
|
var getQueryState = require('./getQueryState.cjs');
|
|
34
36
|
var getInfiniteQueryState = require('./getInfiniteQueryState.cjs');
|
|
35
37
|
var operationInvokeFn = require('./operationInvokeFn.cjs');
|
|
@@ -64,8 +66,10 @@ exports.isMutating = isMutating.isMutating;
|
|
|
64
66
|
exports.useIsFetching = useIsFetching.useIsFetching;
|
|
65
67
|
exports.fetchQuery = fetchQuery.fetchQuery;
|
|
66
68
|
exports.prefetchQuery = prefetchQuery.prefetchQuery;
|
|
69
|
+
exports.ensureQueryData = ensureQueryData.ensureQueryData;
|
|
67
70
|
exports.fetchInfiniteQuery = fetchInfiniteQuery.fetchInfiniteQuery;
|
|
68
71
|
exports.prefetchInfiniteQuery = prefetchInfiniteQuery.prefetchInfiniteQuery;
|
|
72
|
+
exports.ensureInfiniteQueryData = ensureInfiniteQueryData.ensureInfiniteQueryData;
|
|
69
73
|
exports.getQueryState = getQueryState.getQueryState;
|
|
70
74
|
exports.getInfiniteQueryState = getInfiniteQueryState.getInfiniteQueryState;
|
|
71
75
|
exports.operationInvokeFn = operationInvokeFn.operationInvokeFn;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"callQueryClientFetchMethod.cjs","sources":["../../../src/lib/callQueryClientFetchMethod.ts"],"sourcesContent":["import type { QueryClient } from '@tanstack/query-core';\nimport type { CreateAPIQueryClientOptions } from '../qraftAPIClient.js';\nimport type { OperationSchema, RequestFn } from './requestFn.js';\nimport { composeInfiniteQueryKey } from './composeInfiniteQueryKey.js';\nimport { composeQueryKey } from './composeQueryKey.js';\nimport { requestFnResponseResolver } from './requestFnResponseResolver.js';\nimport { shelfMerge } from './shelfMerge.js';\n\n/**\n * Calls a query client fetch method with parameters and options,\n * and automatically composes the `QueryKey` based on the schema and parameters.\n */\nexport function callQueryClientMethodWithQueryKey<\n QFMethod extends QueryKeyMethods,\n>(\n qraftOptions: CreateAPIQueryClientOptions,\n queryFilterMethod: QFMethod,\n schema: OperationSchema,\n infinite: boolean,\n args: QueryClientMethodArgs<QFMethod>\n): ReturnType<(typeof QueryClient.prototype)[QFMethod]> {\n const {\n requestFn: requestFnOption,\n baseUrl: baseUrlOption,\n queryFn: queryFnOption,\n parameters,\n ...options\n } = args[0] ?? {};\n\n const queryClient = qraftOptions.queryClient;\n const baseUrl = baseUrlOption ?? qraftOptions.baseUrl;\n\n if (queryFnOption && requestFnOption) {\n throw new Error(\n 'callQueryClientMethodWithQueryKey: options.queryFn and options.requestFn are mutually exclusive'\n );\n }\n\n const requestFn = requestFnOption ?? qraftOptions.requestFn;\n\n if (options.queryKey && parameters) {\n throw new Error(\n 'callQueryClientMethodWithQueryKey: options.queryKey and options.parameters are mutually exclusive'\n );\n }\n\n const queryFn =\n queryFnOption ??\n (requestFn\n ? // @ts-expect-error - Too complex union to type\n function ({ queryKey: [, queryParams], signal, meta, pageParam }) {\n return requestFn(schema, {\n parameters: infinite\n ? (shelfMerge(2, queryParams, pageParam) as never)\n : queryParams,\n baseUrl,\n signal,\n meta,\n }).then(requestFnResponseResolver, requestFnResponseResolver);\n }\n : undefined);\n\n // @ts-expect-error - Too complex union to type\n return queryClient[queryFilterMethod]({\n ...options,\n queryFn,\n queryKey:\n options.queryKey ??\n (infinite\n ? composeInfiniteQueryKey(schema, parameters)\n : composeQueryKey(schema, parameters)),\n });\n}\n\ntype QueryClientMethodArgs<QMethod extends keyof QueryClientPrototype> = [\n options: Parameters<QueryClientPrototype[QMethod]>[0] & {\n parameters?: unknown;\n baseUrl?: string;\n requestFn?: RequestFn<unknown, unknown>;\n },\n queryClient: QueryClient,\n];\n\ntype QueryKeyMethods =\n | QueryKeyMethod<'fetchQuery'>\n | QueryKeyMethod<'prefetchQuery'>\n | QueryKeyMethod<'fetchInfiniteQuery'>\n | QueryKeyMethod<'prefetchInfiniteQuery'>;\n\ntype QueryClientPrototype = typeof QueryClient.prototype;\n\ntype QueryKeyMethod<QFMethod extends keyof typeof QueryClient.prototype> =\n QFMethod;\n"],"names":["callQueryClientMethodWithQueryKey","qraftOptions","queryFilterMethod","schema","infinite","args","requestFn","requestFnOption","baseUrl","baseUrlOption","queryFn","queryFnOption","parameters","options","queryClient","Error","queryKey","queryParams","signal","meta","pageParam","shelfMerge","then","requestFnResponseResolver","undefined","composeInfiniteQueryKey","composeQueryKey"],"mappings":";;;;;;;AAQA;;;IAIO,SAASA,iCAAAA,CAGdC,YAAyC,EACzCC,iBAA2B,EAC3BC,MAAuB,EACvBC,QAAiB,EACjBC,IAAqC,EAAA;AAErC,IAAA,MAAM,EACJC,SAAWC,EAAAA,eAAe,EAC1BC,OAASC,EAAAA,aAAa,EACtBC,OAASC,EAAAA,aAAa,EACtBC,UAAU,EACV,GAAGC,OACJ,EAAA,GAAGR,IAAI,CAAC,CAAA,CAAE,IAAI,EAAC,CAAA;IAEhB,MAAMS,WAAAA,GAAcb,aAAaa,WAAW,CAAA;IAC5C,MAAMN,OAAAA,GAAU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from '@tanstack/query-core';\nimport type { CreateAPIQueryClientOptions } from '../qraftAPIClient.js';\nimport type { OperationSchema, RequestFn } from './requestFn.js';\nimport { composeInfiniteQueryKey } from './composeInfiniteQueryKey.js';\nimport { composeQueryKey } from './composeQueryKey.js';\nimport { requestFnResponseResolver } from './requestFnResponseResolver.js';\nimport { shelfMerge } from './shelfMerge.js';\n\n/**\n * Calls a query client fetch method with parameters and options,\n * and automatically composes the `QueryKey` based on the schema and parameters.\n */\nexport function callQueryClientMethodWithQueryKey<\n QFMethod extends QueryKeyMethods,\n>(\n qraftOptions: CreateAPIQueryClientOptions,\n queryFilterMethod: QFMethod,\n schema: OperationSchema,\n infinite: boolean,\n args: QueryClientMethodArgs<QFMethod>\n): ReturnType<(typeof QueryClient.prototype)[QFMethod]> {\n const {\n requestFn: requestFnOption,\n baseUrl: baseUrlOption,\n queryFn: queryFnOption,\n parameters,\n ...options\n } = args[0] ?? {};\n\n const queryClient = qraftOptions.queryClient;\n const baseUrl = baseUrlOption ?? qraftOptions.baseUrl;\n\n if (queryFnOption && requestFnOption) {\n throw new Error(\n 'callQueryClientMethodWithQueryKey: options.queryFn and options.requestFn are mutually exclusive'\n );\n }\n\n const requestFn = requestFnOption ?? qraftOptions.requestFn;\n\n if (options.queryKey && parameters) {\n throw new Error(\n 'callQueryClientMethodWithQueryKey: options.queryKey and options.parameters are mutually exclusive'\n );\n }\n\n const queryFn =\n queryFnOption ??\n (requestFn\n ? // @ts-expect-error - Too complex union to type\n function ({ queryKey: [, queryParams], signal, meta, pageParam }) {\n return requestFn(schema, {\n parameters: infinite\n ? (shelfMerge(2, queryParams, pageParam) as never)\n : queryParams,\n baseUrl,\n signal,\n meta,\n }).then(requestFnResponseResolver, requestFnResponseResolver);\n }\n : undefined);\n\n // @ts-expect-error - Too complex union to type\n return queryClient[queryFilterMethod]({\n ...options,\n queryFn,\n queryKey:\n options.queryKey ??\n (infinite\n ? composeInfiniteQueryKey(schema, parameters)\n : composeQueryKey(schema, parameters)),\n });\n}\n\ntype QueryClientMethodArgs<QMethod extends keyof QueryClientPrototype> = [\n options: Parameters<QueryClientPrototype[QMethod]>[0] & {\n parameters?: unknown;\n baseUrl?: string;\n requestFn?: RequestFn<unknown, unknown>;\n },\n queryClient: QueryClient,\n];\n\ntype QueryKeyMethods =\n | QueryKeyMethod<'fetchQuery'>\n | QueryKeyMethod<'prefetchQuery'>\n | QueryKeyMethod<'ensureQueryData'>\n | QueryKeyMethod<'fetchInfiniteQuery'>\n | QueryKeyMethod<'prefetchInfiniteQuery'>\n | QueryKeyMethod<'ensureInfiniteQueryData'>;\n\ntype QueryClientPrototype = typeof QueryClient.prototype;\n\ntype QueryKeyMethod<QFMethod extends keyof typeof QueryClient.prototype> =\n QFMethod;\n"],"names":["callQueryClientMethodWithQueryKey","qraftOptions","queryFilterMethod","schema","infinite","args","requestFn","requestFnOption","baseUrl","baseUrlOption","queryFn","queryFnOption","parameters","options","queryClient","Error","queryKey","queryParams","signal","meta","pageParam","shelfMerge","then","requestFnResponseResolver","undefined","composeInfiniteQueryKey","composeQueryKey"],"mappings":";;;;;;;AAQA;;;IAIO,SAASA,iCAAAA,CAGdC,YAAyC,EACzCC,iBAA2B,EAC3BC,MAAuB,EACvBC,QAAiB,EACjBC,IAAqC,EAAA;AAErC,IAAA,MAAM,EACJC,SAAWC,EAAAA,eAAe,EAC1BC,OAASC,EAAAA,aAAa,EACtBC,OAASC,EAAAA,aAAa,EACtBC,UAAU,EACV,GAAGC,OACJ,EAAA,GAAGR,IAAI,CAAC,CAAA,CAAE,IAAI,EAAC,CAAA;IAEhB,MAAMS,WAAAA,GAAcb,aAAaa,WAAW,CAAA;IAC5C,MAAMN,OAAAA,GAAUC,aAAiBR,IAAAA,YAAAA,CAAaO,OAAO,CAAA;AAErD,IAAA,IAAIG,iBAAiBJ,eAAiB,EAAA;AACpC,QAAA,MAAM,IAAIQ,KACR,CAAA,iGAAA,CAAA,CAAA;AAEJ,KAAA;IAEA,MAAMT,SAAAA,GAAYC,eAAmBN,IAAAA,YAAAA,CAAaK,SAAS,CAAA;IAE3D,IAAIO,OAAAA,CAAQG,QAAQ,IAAIJ,UAAY,EAAA;AAClC,QAAA,MAAM,IAAIG,KACR,CAAA,mGAAA,CAAA,CAAA;AAEJ,KAAA;AAEA,IAAA,MAAML,OACJC,GAAAA,aAAAA,KACCL,SAAAA,GAEG,SAAU,EAAEU,QAAAA,EAAU,GAAGC,WAAAA,CAAY,EAAEC,MAAM,EAAEC,IAAI,EAAEC,SAAS,EAAE,EAAA;AAC9D,QAAA,OAAOd,UAAUH,MAAQ,EAAA;AACvBS,YAAAA,UAAAA,EAAYR,QACPiB,GAAAA,qBAAAA,CAAW,CAAGJ,EAAAA,WAAAA,EAAaG,SAC5BH,CAAAA,GAAAA,WAAAA;AACJT,YAAAA,OAAAA;AACAU,YAAAA,MAAAA;AACAC,YAAAA,IAAAA;SACCG,CAAAA,CAAAA,IAAI,CAACC,mDAA2BA,EAAAA,mDAAAA,CAAAA,CAAAA;AACrC,KAAA,GACAC,SAAQ,CAAA,CAAA;;IAGd,OAAOV,WAAW,CAACZ,iBAAAA,CAAkB,CAAC;AACpC,QAAA,GAAGW,OAAO;AACVH,QAAAA,OAAAA;QACAM,QACEH,EAAAA,OAAAA,CAAQG,QAAQ,KACfZ,QAAAA,GACGqB,gDAAwBtB,MAAQS,EAAAA,UAAAA,CAAAA,GAChCc,+BAAgBvB,CAAAA,MAAAA,EAAQS,UAAU,CAAA,CAAA;AAC1C,KAAA,CAAA,CAAA;AACF;;;;"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var responseUtils = require('./responseUtils.cjs');
|
|
4
|
+
|
|
3
5
|
/**
|
|
4
6
|
* This function is used to make a request to a specified endpoint.
|
|
5
7
|
*
|
|
@@ -21,7 +23,7 @@
|
|
|
21
23
|
}
|
|
22
24
|
/**
|
|
23
25
|
* This function is used to make a request to a specified endpoint.
|
|
24
|
-
* It's
|
|
26
|
+
* It's necessary to create a custom `requestFn` with a custom `urlSerializer`
|
|
25
27
|
* and `bodySerializer`, with the tree-shaking of the default `requestFn`
|
|
26
28
|
* and its serializers.
|
|
27
29
|
*
|
|
@@ -36,19 +38,16 @@
|
|
|
36
38
|
* @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.
|
|
37
39
|
*/ async function baseRequestFn(requestSchema, requestInfo, options) {
|
|
38
40
|
const { parameters, headers, body, ...requestInfoRest } = requestInfo;
|
|
39
|
-
const
|
|
41
|
+
const requestPayload = options.bodySerializer(requestSchema, body);
|
|
40
42
|
const baseFetch = options.fetch ?? fetch;
|
|
41
43
|
return baseFetch(options.urlSerializer(requestSchema, requestInfo), {
|
|
42
44
|
method: requestSchema.method.toUpperCase(),
|
|
43
|
-
body:
|
|
45
|
+
body: requestPayload?.body,
|
|
44
46
|
headers: mergeHeaders({
|
|
45
|
-
Accept: 'application/json'
|
|
46
|
-
|
|
47
|
-
}, headers, parameters?.header, requestBody instanceof FormData ? {
|
|
48
|
-
'Content-Type': null
|
|
49
|
-
} : undefined),
|
|
47
|
+
Accept: 'application/json'
|
|
48
|
+
}, requestPayload?.headers, headers, parameters?.header),
|
|
50
49
|
...requestInfoRest
|
|
51
|
-
}).then(processResponse).catch(resolveResponse);
|
|
50
|
+
}).then(responseUtils.processResponse).catch(responseUtils.resolveResponse);
|
|
52
51
|
}
|
|
53
52
|
/**
|
|
54
53
|
* Serializes the given schema and request payload into a URL string.
|
|
@@ -121,23 +120,68 @@ function mergeHeaders(...allHeaders) {
|
|
|
121
120
|
}
|
|
122
121
|
return headers;
|
|
123
122
|
}
|
|
124
|
-
function bodySerializer(schema,
|
|
125
|
-
if (
|
|
126
|
-
if (
|
|
127
|
-
if (
|
|
128
|
-
|
|
129
|
-
|
|
123
|
+
function bodySerializer(schema, body) {
|
|
124
|
+
if (schema.method === 'get' || schema.method === 'head' || schema.method === 'options') return undefined;
|
|
125
|
+
if (body === undefined || body === null) return undefined;
|
|
126
|
+
if (typeof body === 'string') {
|
|
127
|
+
return {
|
|
128
|
+
body,
|
|
129
|
+
headers: {
|
|
130
|
+
'Content-Type': // prefer text/* media type
|
|
131
|
+
schema.mediaType?.find((mediaType)=>mediaType.includes('text/')) ?? // prefer JSON media type, assume that body is serialized as JSON
|
|
132
|
+
schema.mediaType?.find((mediaType)=>mediaType.includes('/json')) ?? 'text/plain'
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
if (body instanceof FormData) {
|
|
137
|
+
return {
|
|
138
|
+
body,
|
|
139
|
+
headers: {
|
|
140
|
+
// remove `Content-Type` if the serialized body is FormData;
|
|
141
|
+
// the browser will correctly set Content-Type & boundary expression
|
|
142
|
+
'Content-Type': null
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
if (body instanceof Blob) {
|
|
147
|
+
return {
|
|
148
|
+
body,
|
|
149
|
+
headers: {
|
|
150
|
+
'Content-Type': body.type || schema.mediaType?.find((mediaType)=>!(mediaType.includes('text/') && mediaType.includes('/form-data') && mediaType.includes('/json'))) || 'application/octet-stream'
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
let jsonMediaType = null;
|
|
155
|
+
let formDataMediaType = null;
|
|
156
|
+
if (schema.mediaType) {
|
|
157
|
+
for(let i = 0; i < schema.mediaType.length; i++){
|
|
158
|
+
const mediaType = schema.mediaType[i];
|
|
159
|
+
if (mediaType.includes('/json')) jsonMediaType = mediaType;
|
|
160
|
+
else if (mediaType.includes('/form-data')) formDataMediaType = mediaType;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (formDataMediaType) {
|
|
164
|
+
if (!jsonMediaType || // Prefer FormData serialization if one of the fields is a Blob
|
|
165
|
+
Object.values(body).some((value)=>value instanceof Blob)) {
|
|
166
|
+
return {
|
|
167
|
+
body: getRequestBodyFormData(body),
|
|
168
|
+
headers: {
|
|
169
|
+
// remove `Content-Type` if the serialized body is FormData;
|
|
170
|
+
// the browser will correctly set Content-Type & boundary expression
|
|
171
|
+
'Content-Type': null
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
130
175
|
}
|
|
131
|
-
return
|
|
176
|
+
return {
|
|
177
|
+
body: JSON.stringify(body),
|
|
178
|
+
headers: {
|
|
179
|
+
'Content-Type': jsonMediaType ?? 'application/json'
|
|
180
|
+
}
|
|
181
|
+
};
|
|
132
182
|
}
|
|
133
|
-
function getRequestBodyFormData(
|
|
183
|
+
function getRequestBodyFormData(body) {
|
|
134
184
|
if (body instanceof FormData) return body;
|
|
135
|
-
if (body === null) return;
|
|
136
|
-
if (body instanceof Blob) throw new Error('Blob not supported in form-data');
|
|
137
|
-
if (body instanceof ArrayBuffer) throw new Error('ArrayBuffer not supported in form-data');
|
|
138
|
-
if (body instanceof URLSearchParams) throw new Error('URLSearchParams not supported in form-data');
|
|
139
|
-
if (body instanceof ReadableStream) throw new Error('ReadableStream not supported in form-data');
|
|
140
|
-
if (typeof body === 'string') throw new Error('String not supported in form-data');
|
|
141
185
|
if (typeof body !== 'object') throw new Error(`Unsupported body type ${typeof body} in form-data.`);
|
|
142
186
|
const formData = new FormData();
|
|
143
187
|
const process = (key, value)=>{
|
|
@@ -156,47 +200,6 @@ function getRequestBodyFormData({ body }) {
|
|
|
156
200
|
});
|
|
157
201
|
return formData;
|
|
158
202
|
}
|
|
159
|
-
function getBodyContentType(body) {
|
|
160
|
-
if (!body) return;
|
|
161
|
-
if (body instanceof Blob) return body.type || 'application/octet-stream';
|
|
162
|
-
if (typeof body === 'string') return 'text/plain';
|
|
163
|
-
if (!(body instanceof FormData)) return 'application/json';
|
|
164
|
-
}
|
|
165
|
-
async function processResponse(response) {
|
|
166
|
-
if (response.status === 204 || response.headers.get('Content-Length') === '0') return response.ok ? {
|
|
167
|
-
data: {},
|
|
168
|
-
response
|
|
169
|
-
} : {
|
|
170
|
-
error: {},
|
|
171
|
-
response
|
|
172
|
-
};
|
|
173
|
-
if (isJsonResponse(response)) {
|
|
174
|
-
// clone response before parsing every time to allow multiple reads
|
|
175
|
-
const jsonResponse = response.clone().json();
|
|
176
|
-
return resolveResponse(response, response.ok ? jsonResponse : Promise.reject(await jsonResponse));
|
|
177
|
-
}
|
|
178
|
-
const jsonResponse = new Promise((resolve, reject)=>// attempt to parse JSON for successful responses, otherwise fail
|
|
179
|
-
response.clone().text().then(JSON.parse).then(resolve, reject));
|
|
180
|
-
return resolveResponse(response, response.ok ? jsonResponse : Promise.reject(await jsonResponse));
|
|
181
|
-
}
|
|
182
|
-
function isJsonResponse(response) {
|
|
183
|
-
const contentType = response.headers.get('Content-Type')?.toLowerCase();
|
|
184
|
-
return contentType?.includes('/json') || contentType?.includes('+json');
|
|
185
|
-
}
|
|
186
|
-
function resolveResponse(responseToReturn, responsePromise) {
|
|
187
|
-
if (!responsePromise) return Promise.reject({
|
|
188
|
-
error: responseToReturn,
|
|
189
|
-
response: undefined,
|
|
190
|
-
data: undefined
|
|
191
|
-
});
|
|
192
|
-
return responsePromise.then((data)=>({
|
|
193
|
-
data,
|
|
194
|
-
response: responseToReturn
|
|
195
|
-
})).catch((error)=>({
|
|
196
|
-
error,
|
|
197
|
-
response: responseToReturn
|
|
198
|
-
}));
|
|
199
|
-
}
|
|
200
203
|
|
|
201
204
|
exports.baseRequestFn = baseRequestFn;
|
|
202
205
|
exports.bodySerializer = bodySerializer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestFn.cjs","sources":["../../../src/lib/requestFn.ts"],"sourcesContent":["import type {\n HeadersOptions,\n OperationSchema,\n RequestFnInfo,\n RequestFnOptions,\n RequestFnResponse,\n} from '@openapi-qraft/tanstack-query-react-types';\n\n/**\n * This function is used to make a request to a specified endpoint.\n *\n * @template T The expected return type of the request.\n *\n * @param schema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param [options] Optional. Additional options for the request. It includes custom urlSerializer, bodySerializer, and fetch function.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function requestFn<TData, TError>(\n schema: OperationSchema,\n requestInfo: RequestFnInfo,\n options?: RequestFnOptions\n): Promise<RequestFnResponse<TData, TError>> {\n return baseRequestFn<TData, TError>(schema, requestInfo, {\n urlSerializer,\n bodySerializer,\n ...options,\n });\n}\n\n/**\n * This function is used to make a request to a specified endpoint.\n * It's needed to create a custom `requestFn` with a custom `urlSerializer`\n * and `bodySerializer`, with the tree-shaking of the default `requestFn`\n * and its serializers.\n *\n * @template T The expected return type of the request.\n *\n * @param requestSchema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param options The options for the request. It includes urlSerializer, bodySerializer, and fetch function. The 'urlSerializer' and 'bodySerializer' are required.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function baseRequestFn<TData, TError>(\n requestSchema: OperationSchema,\n requestInfo: RequestFnInfo,\n options: WithRequired<RequestFnOptions, 'urlSerializer' | 'bodySerializer'>\n): Promise<RequestFnResponse<TData, TError>> {\n const { parameters, headers, body, ...requestInfoRest } = requestInfo;\n\n const requestBody = options.bodySerializer(requestSchema, requestInfo);\n\n const baseFetch = options.fetch ?? fetch;\n\n return baseFetch(options.urlSerializer(requestSchema, requestInfo), {\n method: requestSchema.method.toUpperCase(),\n body: requestBody,\n headers: mergeHeaders(\n {\n Accept: 'application/json',\n 'Content-Type': requestSchema.mediaType ?? getBodyContentType(body),\n },\n headers,\n parameters?.header,\n requestBody instanceof FormData\n ? // remove `Content-Type` if the serialized body is FormData; the browser will correctly set Content-Type & boundary expression\n { 'Content-Type': null }\n : undefined\n ),\n ...requestInfoRest,\n })\n .then(processResponse as typeof processResponse<TData, TError>)\n .catch(resolveResponse as typeof resolveResponse<TData, TError>);\n}\n\n/**\n * Serializes the given schema and request payload into a URL string.\n *\n * This function is implemented according to the URI Template standard\n * defined in RFC 6570. It supports the expansion of path and query parameters,\n * correctly handling empty arrays, `null`, and `undefined` values by ignoring\n * them during the expansion process, as specified by the standard.\n *\n * For more information, refer to the official documentation:\n * https://datatracker.ietf.org/doc/html/rfc6570\n *\n * @param schema - The operation schema containing the URL template and method.\n * @param info - The request payload including baseUrl, path parameters, and query parameters.\n * @returns The fully constructed URL string.\n */\nexport function urlSerializer(\n schema: OperationSchema,\n info: Pick<RequestFnInfo, 'baseUrl' | 'parameters'>\n): string {\n const path = schema.url.replace(\n /{(.*?)}/g,\n (substring: string, group: string) => {\n if (\n info.parameters?.path &&\n Object.prototype.hasOwnProperty.call(info.parameters.path, group)\n ) {\n return encodeURI(String(info.parameters?.path[group]));\n }\n return substring;\n }\n );\n\n const baseUrl = info.baseUrl ?? '';\n\n if (info.parameters?.query) {\n return `${baseUrl}${path}${getQueryString(info.parameters.query)}`;\n }\n\n return `${baseUrl}${path}`;\n}\n\nfunction getQueryString(params: Record<string, any>): string {\n const qs: string[] = [];\n\n const append = (key: string, value: any) => {\n qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n };\n\n const process = (key: string, value: any) => {\n if (typeof value === 'undefined' || value === null) return;\n\n if (Array.isArray(value)) {\n value.forEach((v) => {\n process(key, v);\n });\n } else if (typeof value === 'object') {\n Object.entries(value).forEach(([k, v]) => {\n process(`${key}[${k}]`, v);\n });\n } else {\n append(key, value);\n }\n };\n\n Object.entries(params).forEach(([key, value]) => {\n process(key, value);\n });\n\n if (qs.length > 0) {\n return `?${qs.join('&')}`;\n }\n\n return '';\n}\n\nexport function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]) {\n const headers = new Headers();\n\n for (const headerSet of allHeaders) {\n if (!headerSet || typeof headerSet !== 'object') {\n continue;\n }\n\n const headersIterator =\n headerSet instanceof Headers\n ? headerSet.entries()\n : Object.entries(headerSet);\n\n for (const [headerKey, headerValue] of headersIterator) {\n if (headerValue === null) {\n headers.delete(headerKey);\n } else if (headerValue !== undefined) {\n headers.set(headerKey, headerValue);\n }\n }\n }\n\n return headers;\n}\n\nexport function bodySerializer(schema: OperationSchema, info: RequestFnInfo) {\n if (info.body === undefined) return;\n\n if (\n schema.method === 'get' ||\n schema.method === 'head' ||\n schema.method === 'options'\n )\n return;\n\n if (schema.mediaType?.includes('/form-data'))\n return getRequestBodyFormData(info);\n\n if (\n !schema.mediaType?.includes('/json') &&\n (typeof info.body === 'string' ||\n info.body instanceof Blob ||\n info.body instanceof FormData)\n ) {\n return info.body;\n }\n\n return JSON.stringify(info.body);\n}\n\nfunction getRequestBodyFormData({\n body,\n}: Pick<RequestFnInfo, 'body'>): FormData | undefined {\n if (body instanceof FormData) return body;\n if (body === null) return;\n\n if (body instanceof Blob) throw new Error('Blob not supported in form-data');\n if (body instanceof ArrayBuffer)\n throw new Error('ArrayBuffer not supported in form-data');\n if (body instanceof URLSearchParams)\n throw new Error('URLSearchParams not supported in form-data');\n if (body instanceof ReadableStream)\n throw new Error('ReadableStream not supported in form-data');\n if (typeof body === 'string')\n throw new Error('String not supported in form-data');\n if (typeof body !== 'object')\n throw new Error(`Unsupported body type ${typeof body} in form-data.`);\n\n const formData = new FormData();\n\n const process = (key: string, value: any) => {\n if (typeof value === 'string' || value instanceof Blob) {\n formData.append(key, value);\n } else {\n formData.append(key, JSON.stringify(value));\n }\n };\n\n Object.entries(body)\n .filter(([_, value]) => typeof value !== 'undefined' && value !== null)\n .forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => process(key, v));\n } else {\n process(key, value);\n }\n });\n\n return formData;\n}\n\nfunction getBodyContentType(body: RequestFnInfo['body']) {\n if (!body) return;\n if (body instanceof Blob) return body.type || 'application/octet-stream';\n if (typeof body === 'string') return 'text/plain';\n if (!(body instanceof FormData)) return 'application/json';\n}\n\nasync function processResponse<TData, TError>(\n response: Response\n): Promise<RequestFnResponse<TData, TError>> {\n if (response.status === 204 || response.headers.get('Content-Length') === '0')\n return (\n response.ok ? { data: {}, response } : { error: {}, response }\n ) as RequestFnResponse<TData, TError>;\n\n if (isJsonResponse(response)) {\n // clone response before parsing every time to allow multiple reads\n const jsonResponse = response.clone().json();\n return resolveResponse(\n response,\n response.ok ? jsonResponse : Promise.reject(await jsonResponse)\n );\n }\n\n const jsonResponse = new Promise<TData>((resolve, reject) =>\n // attempt to parse JSON for successful responses, otherwise fail\n response.clone().text().then(JSON.parse).then(resolve, reject)\n );\n\n return resolveResponse(\n response,\n response.ok ? jsonResponse : Promise.reject(await jsonResponse)\n );\n}\n\nfunction isJsonResponse(response: Response) {\n const contentType = response.headers.get('Content-Type')?.toLowerCase();\n return contentType?.includes('/json') || contentType?.includes('+json');\n}\n\nfunction resolveResponse<TData, TError>(\n error: Error\n): Promise<RequestFnResponse<TData, TError>>;\nfunction resolveResponse<TData, TError>(\n responseToReturn: Response,\n responsePromise: Promise<TData>\n): Promise<RequestFnResponse<TData, TError>>;\nfunction resolveResponse<TData, TError>(\n responseToReturn: Response | Error,\n responsePromise?: Promise<TData>\n): Promise<RequestFnResponse<TData, TError>> {\n if (!responsePromise)\n return Promise.reject({\n error: responseToReturn,\n response: undefined,\n data: undefined,\n });\n\n return responsePromise\n .then(\n (data) =>\n ({ data, response: responseToReturn }) as RequestFnResponse<\n TData,\n TError\n >\n )\n .catch(\n (error) =>\n ({ error, response: responseToReturn }) as RequestFnResponse<\n TData,\n TError\n >\n );\n}\n\ntype WithRequired<T, K extends keyof T> = T & {\n [_ in K]: {};\n};\n\nexport type {\n RequestFn,\n RequestFnResponse,\n HeadersOptions,\n RequestFnOptions,\n RequestFnInfo,\n OperationSchema,\n} from '@openapi-qraft/tanstack-query-react-types';\n\n/**\n * @deprecated use `RequestFnInfo` instead\n */\nexport type RequestFnPayload = RequestFnInfo;\n"],"names":["requestFn","schema","requestInfo","options","baseRequestFn","urlSerializer","bodySerializer","requestSchema","parameters","headers","body","requestInfoRest","requestBody","baseFetch","fetch","method","toUpperCase","mergeHeaders","Accept","mediaType","getBodyContentType","header","FormData","undefined","then","processResponse","catch","resolveResponse","info","path","url","replace","substring","group","Object","prototype","hasOwnProperty","call","encodeURI","String","baseUrl","query","getQueryString","params","qs","append","key","value","push","encodeURIComponent","process","Array","isArray","forEach","v","entries","k","length","join","allHeaders","Headers","headerSet","headersIterator","headerKey","headerValue","delete","set","includes","getRequestBodyFormData","Blob","JSON","stringify","Error","ArrayBuffer","URLSearchParams","ReadableStream","formData","filter","_","type","response","status","get","ok","data","error","isJsonResponse","jsonResponse","clone","json","Promise","reject","resolve","text","parse","contentType","toLowerCase","responseToReturn","responsePromise"],"mappings":";;AAQA;;;;;;;;;;;;AAYC,IACM,eAAeA,SAAAA,CACpBC,MAAuB,EACvBC,WAA0B,EAC1BC,OAA0B,EAAA;IAE1B,OAAOC,aAAAA,CAA6BH,QAAQC,WAAa,EAAA;AACvDG,QAAAA,aAAAA;AACAC,QAAAA,cAAAA;AACA,QAAA,GAAGH,OAAO;AACZ,KAAA,CAAA,CAAA;AACF,CAAA;AAEA;;;;;;;;;;;;;;;AAeC,IACM,eAAeC,aAAAA,CACpBG,aAA8B,EAC9BL,WAA0B,EAC1BC,OAA2E,EAAA;IAE3E,MAAM,EAAEK,UAAU,EAAEC,OAAO,EAAEC,IAAI,EAAE,GAAGC,eAAAA,EAAiB,GAAGT,WAAAA,CAAAA;AAE1D,IAAA,MAAMU,WAAcT,GAAAA,OAAAA,CAAQG,cAAc,CAACC,aAAeL,EAAAA,WAAAA,CAAAA,CAAAA;IAE1D,MAAMW,SAAAA,GAAYV,OAAQW,CAAAA,KAAK,IAAIA,KAAAA,CAAAA;AAEnC,IAAA,OAAOD,SAAUV,CAAAA,OAAAA,CAAQE,aAAa,CAACE,eAAeL,WAAc,CAAA,EAAA;QAClEa,MAAQR,EAAAA,aAAAA,CAAcQ,M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AeN,QAAkB,EAAA;AACxC,IAAA,MAAMe,cAAcf,QAASvE,CAAAA,OAAO,CAACyE,GAAG,CAAC,cAAiBc,CAAAA,EAAAA,WAAAA,EAAAA,CAAAA;AAC1D,IAAA,OAAOD,WAAa5B,EAAAA,QAAAA,CAAS,OAAY4B,CAAAA,IAAAA,WAAAA,EAAa5B,QAAS,CAAA,OAAA,CAAA,CAAA;AACjE,CAAA;AASA,SAASxC,eAAAA,CACPsE,gBAAkC,EAClCC,eAAgC,EAAA;AAEhC,IAAA,IAAI,CAACA,eAAAA,EACH,OAAOR,OAAAA,CAAQC,MAAM,CAAC;QACpBN,KAAOY,EAAAA,gBAAAA;QACPjB,QAAUzD,EAAAA,SAAAA;QACV6D,IAAM7D,EAAAA,SAAAA;AACR,KAAA,CAAA,CAAA;AAEF,IAAA,OAAO2E,eACJ1E,CAAAA,IAAI,CACH,CAAC4D,QACE;AAAEA,YAAAA,IAAAA;YAAMJ,QAAUiB,EAAAA,gBAAAA;AAAiB,SAAA,CAKvCvE,CAAAA,CAAAA,KAAK,CACJ,CAAC2D,SACE;AAAEA,YAAAA,KAAAA;YAAOL,QAAUiB,EAAAA,gBAAAA;SAAiB,CAAA,CAAA,CAAA;AAK7C;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"requestFn.cjs","sources":["../../../src/lib/requestFn.ts"],"sourcesContent":["import type {\n HeadersOptions,\n OperationSchema,\n RequestFnInfo,\n RequestFnOptions,\n RequestFnResponse,\n} from '@openapi-qraft/tanstack-query-react-types';\nimport { processResponse, resolveResponse } from './responseUtils.js';\n\n/**\n * This function is used to make a request to a specified endpoint.\n *\n * @template T The expected return type of the request.\n *\n * @param schema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param [options] Optional. Additional options for the request. It includes custom urlSerializer, bodySerializer, and fetch function.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function requestFn<TData, TError>(\n schema: OperationSchema,\n requestInfo: RequestFnInfo,\n options?: RequestFnOptions\n): Promise<RequestFnResponse<TData, TError>> {\n return baseRequestFn<TData, TError>(schema, requestInfo, {\n urlSerializer,\n bodySerializer,\n ...options,\n });\n}\n\n/**\n * This function is used to make a request to a specified endpoint.\n * It's necessary to create a custom `requestFn` with a custom `urlSerializer`\n * and `bodySerializer`, with the tree-shaking of the default `requestFn`\n * and its serializers.\n *\n * @template T The expected return type of the request.\n *\n * @param requestSchema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param options The options for the request. It includes urlSerializer, bodySerializer, and fetch function. The 'urlSerializer' and 'bodySerializer' are required.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function baseRequestFn<TData, TError>(\n requestSchema: OperationSchema,\n requestInfo: RequestFnInfo,\n options: WithRequired<RequestFnOptions, 'urlSerializer' | 'bodySerializer'>\n): Promise<RequestFnResponse<TData, TError>> {\n const { parameters, headers, body, ...requestInfoRest } = requestInfo;\n\n const requestPayload = options.bodySerializer(requestSchema, body);\n\n const baseFetch = options.fetch ?? fetch;\n\n return baseFetch(options.urlSerializer(requestSchema, requestInfo), {\n method: requestSchema.method.toUpperCase(),\n body: requestPayload?.body,\n headers: mergeHeaders(\n { Accept: 'application/json' },\n requestPayload?.headers,\n headers,\n parameters?.header\n ),\n ...requestInfoRest,\n })\n .then(processResponse as typeof processResponse<TData, TError>)\n .catch(resolveResponse as typeof resolveResponse<TData, TError>);\n}\n\n/**\n * Serializes the given schema and request payload into a URL string.\n *\n * This function is implemented according to the URI Template standard\n * defined in RFC 6570. It supports the expansion of path and query parameters,\n * correctly handling empty arrays, `null`, and `undefined` values by ignoring\n * them during the expansion process, as specified by the standard.\n *\n * For more information, refer to the official documentation:\n * https://datatracker.ietf.org/doc/html/rfc6570\n *\n * @param schema - The operation schema containing the URL template and method.\n * @param info - The request payload including baseUrl, path parameters, and query parameters.\n * @returns The fully constructed URL string.\n */\nexport function urlSerializer(\n schema: OperationSchema,\n info: Pick<RequestFnInfo, 'baseUrl' | 'parameters'>\n): string {\n const path = schema.url.replace(\n /{(.*?)}/g,\n (substring: string, group: string) => {\n if (\n info.parameters?.path &&\n Object.prototype.hasOwnProperty.call(info.parameters.path, group)\n ) {\n return encodeURI(String(info.parameters?.path[group]));\n }\n return substring;\n }\n );\n\n const baseUrl = info.baseUrl ?? '';\n\n if (info.parameters?.query) {\n return `${baseUrl}${path}${getQueryString(info.parameters.query)}`;\n }\n\n return `${baseUrl}${path}`;\n}\n\nfunction getQueryString(params: Record<string, any>): string {\n const qs: string[] = [];\n\n const append = (key: string, value: any) => {\n qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n };\n\n const process = (key: string, value: any) => {\n if (typeof value === 'undefined' || value === null) return;\n\n if (Array.isArray(value)) {\n value.forEach((v) => {\n process(key, v);\n });\n } else if (typeof value === 'object') {\n Object.entries(value).forEach(([k, v]) => {\n process(`${key}[${k}]`, v);\n });\n } else {\n append(key, value);\n }\n };\n\n Object.entries(params).forEach(([key, value]) => {\n process(key, value);\n });\n\n if (qs.length > 0) {\n return `?${qs.join('&')}`;\n }\n\n return '';\n}\n\nexport function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]) {\n const headers = new Headers();\n\n for (const headerSet of allHeaders) {\n if (!headerSet || typeof headerSet !== 'object') {\n continue;\n }\n\n const headersIterator =\n headerSet instanceof Headers\n ? headerSet.entries()\n : Object.entries(headerSet);\n\n for (const [headerKey, headerValue] of headersIterator) {\n if (headerValue === null) {\n headers.delete(headerKey);\n } else if (headerValue !== undefined) {\n headers.set(headerKey, headerValue);\n }\n }\n }\n\n return headers;\n}\n\nexport function bodySerializer(\n schema: OperationSchema,\n body: RequestFnInfo['body']\n) {\n if (\n schema.method === 'get' ||\n schema.method === 'head' ||\n schema.method === 'options'\n )\n return undefined;\n\n if (body === undefined || body === null) return undefined;\n\n if (typeof body === 'string') {\n return {\n body,\n headers: {\n 'Content-Type':\n // prefer text/* media type\n schema.mediaType?.find((mediaType) => mediaType.includes('text/')) ??\n // prefer JSON media type, assume that body is serialized as JSON\n schema.mediaType?.find((mediaType) => mediaType.includes('/json')) ??\n 'text/plain',\n },\n };\n }\n\n if (body instanceof FormData) {\n return {\n body,\n headers: {\n // remove `Content-Type` if the serialized body is FormData;\n // the browser will correctly set Content-Type & boundary expression\n 'Content-Type': null,\n },\n };\n }\n\n if (body instanceof Blob) {\n return {\n body,\n headers: {\n 'Content-Type':\n body.type ||\n schema.mediaType?.find(\n (mediaType) =>\n !(\n mediaType.includes('text/') &&\n mediaType.includes('/form-data') &&\n mediaType.includes('/json')\n )\n ) ||\n 'application/octet-stream',\n },\n };\n }\n\n let jsonMediaType: string | null = null;\n let formDataMediaType: string | null = null;\n\n if (schema.mediaType) {\n for (let i = 0; i < schema.mediaType.length; i++) {\n const mediaType = schema.mediaType[i];\n if (mediaType.includes('/json')) jsonMediaType = mediaType;\n else if (mediaType.includes('/form-data')) formDataMediaType = mediaType;\n }\n }\n\n if (formDataMediaType) {\n if (\n !jsonMediaType ||\n // Prefer FormData serialization if one of the fields is a Blob\n Object.values(body).some((value) => value instanceof Blob)\n ) {\n return {\n body: getRequestBodyFormData(body),\n headers: {\n // remove `Content-Type` if the serialized body is FormData;\n // the browser will correctly set Content-Type & boundary expression\n 'Content-Type': null,\n },\n };\n }\n }\n\n return {\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': jsonMediaType ?? 'application/json',\n },\n };\n}\n\nfunction getRequestBodyFormData(\n body: NonNullable<RequestFnInfo['body']>\n): FormData {\n if (body instanceof FormData) return body;\n if (typeof body !== 'object')\n throw new Error(`Unsupported body type ${typeof body} in form-data.`);\n\n const formData = new FormData();\n\n const process = (key: string, value: any) => {\n if (typeof value === 'string' || value instanceof Blob) {\n formData.append(key, value);\n } else {\n formData.append(key, JSON.stringify(value));\n }\n };\n\n Object.entries(body)\n .filter(([_, value]) => typeof value !== 'undefined' && value !== null)\n .forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => process(key, v));\n } else {\n process(key, value);\n }\n });\n\n return formData;\n}\n\ntype WithRequired<T, K extends keyof T> = T & {\n [_ in K]: {};\n};\n\nexport type {\n RequestFn,\n RequestFnResponse,\n HeadersOptions,\n RequestFnOptions,\n RequestFnInfo,\n OperationSchema,\n} from '@openapi-qraft/tanstack-query-react-types';\n\n/**\n * @deprecated use `RequestFnInfo` instead\n */\nexport type RequestFnPayload = RequestFnInfo;\n"],"names":["requestFn","schema","requestInfo","options","baseRequestFn","urlSerializer","bodySerializer","requestSchema","parameters","headers","body","requestInfoRest","requestPayload","baseFetch","fetch","method","toUpperCase","mergeHeaders","Accept","header","then","processResponse","catch","resolveResponse","info","path","url","replace","substring","group","Object","prototype","hasOwnProperty","call","encodeURI","String","baseUrl","query","getQueryString","params","qs","append","key","value","push","encodeURIComponent","process","Array","isArray","forEach","v","entries","k","length","join","allHeaders","Headers","headerSet","headersIterator","headerKey","headerValue","delete","undefined","set","mediaType","find","includes","FormData","Blob","type","jsonMediaType","formDataMediaType","i","values","some","getRequestBodyFormData","JSON","stringify","Error","formData","filter","_"],"mappings":";;;;AASA;;;;;;;;;;;;AAYC,IACM,eAAeA,SAAAA,CACpBC,MAAuB,EACvBC,WAA0B,EAC1BC,OAA0B,EAAA;IAE1B,OAAOC,aAAAA,CAA6BH,QAAQC,WAAa,EAAA;AACvDG,QAAAA,aAAAA;AACAC,QAAAA,cAAAA;AACA,QAAA,GAAGH,OAAO;AACZ,KAAA,CAAA,CAAA;AACF,CAAA;AAEA;;;;;;;;;;;;;;;AAeC,IACM,eAAeC,aAAAA,CACpBG,aAA8B,EAC9BL,WAA0B,EAC1BC,OAA2E,EAAA;IAE3E,MAAM,EA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|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Processes the response from the server.
|
|
5
|
+
* @beta
|
|
6
|
+
*/ async function processResponse(response) {
|
|
7
|
+
if (response.status === 204 || response.headers.get('Content-Length') === '0') return response.ok ? {
|
|
8
|
+
data: {},
|
|
9
|
+
response
|
|
10
|
+
} : {
|
|
11
|
+
error: {},
|
|
12
|
+
response
|
|
13
|
+
};
|
|
14
|
+
const contentType = response.headers.get('Content-Type')?.toLowerCase();
|
|
15
|
+
const isJsonResponse = contentType?.includes('/json') || contentType?.includes('+json');
|
|
16
|
+
if (isJsonResponse) {
|
|
17
|
+
// clone response before parsing every time to allow multiple reads
|
|
18
|
+
const jsonResponse = response.clone().json();
|
|
19
|
+
return resolveResponse(response, response.ok ? jsonResponse : Promise.reject(await jsonResponse));
|
|
20
|
+
}
|
|
21
|
+
const textResponse = response.clone().text();
|
|
22
|
+
return resolveResponse(response, response.ok ? textResponse : Promise.reject(await textResponse));
|
|
23
|
+
}
|
|
24
|
+
function resolveResponse(responseToReturn, responsePromise) {
|
|
25
|
+
if (!responsePromise) return Promise.reject({
|
|
26
|
+
error: responseToReturn,
|
|
27
|
+
response: undefined,
|
|
28
|
+
data: undefined
|
|
29
|
+
});
|
|
30
|
+
return responsePromise.then((data)=>({
|
|
31
|
+
data,
|
|
32
|
+
response: responseToReturn
|
|
33
|
+
})).catch((error)=>({
|
|
34
|
+
error,
|
|
35
|
+
response: responseToReturn
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
exports.processResponse = processResponse;
|
|
40
|
+
exports.resolveResponse = resolveResponse;
|
|
41
|
+
//# sourceMappingURL=responseUtils.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"responseUtils.cjs","sources":["../../../src/lib/responseUtils.ts"],"sourcesContent":["import type { RequestFnResponse } from '@openapi-qraft/tanstack-query-react-types';\n\n/**\n * Processes the response from the server.\n * @beta\n */\nexport async function processResponse<TData, TError>(\n response: Response\n): Promise<RequestFnResponse<TData, TError>> {\n if (response.status === 204 || response.headers.get('Content-Length') === '0')\n return (\n response.ok ? { data: {}, response } : { error: {}, response }\n ) as RequestFnResponse<TData, TError>;\n\n const contentType = response.headers.get('Content-Type')?.toLowerCase();\n\n const isJsonResponse =\n contentType?.includes('/json') || contentType?.includes('+json');\n\n if (isJsonResponse) {\n // clone response before parsing every time to allow multiple reads\n const jsonResponse = response.clone().json();\n return resolveResponse(\n response,\n response.ok ? jsonResponse : Promise.reject(await jsonResponse)\n );\n }\n\n const textResponse = response.clone().text() as Promise<TData>;\n\n return resolveResponse(\n response,\n response.ok ? textResponse : Promise.reject(await textResponse)\n );\n}\n\n/**\n * Resolves the response from the server.\n * @beta\n */\nexport function resolveResponse<TData, TError>(\n error: Error\n): Promise<RequestFnResponse<TData, TError>>;\nexport function resolveResponse<TData, TError>(\n responseToReturn: Response,\n responsePromise: Promise<TData>\n): Promise<RequestFnResponse<TData, TError>>;\nexport function resolveResponse<TData, TError>(\n responseToReturn: Response | Error,\n responsePromise?: Promise<TData>\n): Promise<RequestFnResponse<TData, TError>> {\n if (!responsePromise)\n return Promise.reject({\n error: responseToReturn,\n response: undefined,\n data: undefined,\n });\n\n return responsePromise\n .then(\n (data) =>\n ({ data, response: responseToReturn }) as RequestFnResponse<\n TData,\n TError\n >\n )\n .catch(\n (error) =>\n ({ error, response: responseToReturn }) as RequestFnResponse<\n TData,\n TError\n >\n );\n}\n"],"names":["processResponse","response","status","headers","get","ok","data","error","contentType","toLowerCase","isJsonResponse","includes","jsonResponse","clone","json","resolveResponse","Promise","reject","textResponse","text","responseToReturn","responsePromise","undefined","then","catch"],"mappings":";;AAEA;;;IAIO,eAAeA,eAAAA,CACpBC,QAAkB,EAAA;AAElB,IAAA,IAAIA,QAASC,CAAAA,MAAM,KAAK,GAAA,IAAOD,SAASE,OAAO,CAACC,GAAG,CAAC,gBAAsB,CAAA,KAAA,GAAA,EACxE,OACEH,Q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AAAA;AAAiB,SAAA,CAKvCI,CAAAA,CAAAA,KAAK,CACJ,CAACjB,SACE;AAAEA,YAAAA,KAAAA;YAAON,QAAUmB,EAAAA,gBAAAA;SAAiB,CAAA,CAAA,CAAA;AAK7C;;;;;"}
|
|
@@ -13,8 +13,8 @@ function qraftAPIClient(services, callbacks, options) {
|
|
|
13
13
|
assertValidCallbackName(callbackName, callbacks);
|
|
14
14
|
const serviceOperation = getByPath(services, path);
|
|
15
15
|
if (!isServiceOperation(serviceOperation)) throw new Error(`Service operation not found: ${path.join('.')}`);
|
|
16
|
-
if (callbackName !== 'operationInvokeFn' && callbackName !== 'getQueryKey' && callbackName !== 'getMutationKey') {
|
|
17
|
-
if (!options || !('queryClient' in options && options.queryClient)) throw new Error(`'qraft.<service>.<operation>.${String(callbackName)}()' requires 'queryClient' in options.`);
|
|
16
|
+
if (callbackName !== 'operationInvokeFn' && callbackName !== 'getQueryKey' && callbackName !== 'getMutationKey' && callbackName !== 'getInfiniteQueryKey') {
|
|
17
|
+
if (!options || !('queryClient' in options && options.queryClient)) throw new Error(`'qraft.<service>.<operation>.${String(callbackName)}()' requires 'queryClient' in 'createAPIClient(...)' options.`);
|
|
18
18
|
}
|
|
19
19
|
// @ts-expect-error - Too complex union type
|
|
20
20
|
return callbacks[callbackName](options, serviceOperation.schema, args);
|