@geekmidas/client 0.0.1

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.
Files changed (51) hide show
  1. package/README.md +518 -0
  2. package/dist/chunk-CUT6urMc.cjs +30 -0
  3. package/dist/fetcher-DLDD_7Sa.mjs +86 -0
  4. package/dist/fetcher-DLDD_7Sa.mjs.map +1 -0
  5. package/dist/fetcher-KdwHgdAl.cjs +98 -0
  6. package/dist/fetcher-KdwHgdAl.cjs.map +1 -0
  7. package/dist/fetcher.cjs +4 -0
  8. package/dist/fetcher.d.cts +18 -0
  9. package/dist/fetcher.d.mts +18 -0
  10. package/dist/fetcher.mjs +3 -0
  11. package/dist/openapi-hooks.cjs +44 -0
  12. package/dist/openapi-hooks.cjs.map +1 -0
  13. package/dist/openapi-hooks.d.cts +99 -0
  14. package/dist/openapi-hooks.d.mts +99 -0
  15. package/dist/openapi-hooks.mjs +43 -0
  16. package/dist/openapi-hooks.mjs.map +1 -0
  17. package/dist/openapi-types.d.cjs +0 -0
  18. package/dist/openapi-types.d.cts +443 -0
  19. package/dist/openapi-types.d.mts +443 -0
  20. package/dist/openapi.cjs +526 -0
  21. package/dist/openapi.cjs.map +1 -0
  22. package/dist/openapi.mjs +501 -0
  23. package/dist/openapi.mjs.map +1 -0
  24. package/dist/react-query.cjs +147 -0
  25. package/dist/react-query.cjs.map +1 -0
  26. package/dist/react-query.d.cts +77 -0
  27. package/dist/react-query.d.mts +77 -0
  28. package/dist/react-query.mjs +141 -0
  29. package/dist/react-query.mjs.map +1 -0
  30. package/dist/types-csACmD6U.d.cts +68 -0
  31. package/dist/types-tMp85Lt_.d.mts +68 -0
  32. package/dist/types.cjs +0 -0
  33. package/dist/types.d.cts +2 -0
  34. package/dist/types.d.mts +2 -0
  35. package/dist/types.mjs +0 -0
  36. package/package.json +59 -0
  37. package/src/__tests__/fetcher.spec.ts +409 -0
  38. package/src/__tests__/method-restrictions.spec.tsx +227 -0
  39. package/src/__tests__/openapi-hooks.spec.tsx +558 -0
  40. package/src/__tests__/react-query-infinite.spec.tsx +1003 -0
  41. package/src/__tests__/react-query-invalidation.spec.tsx +238 -0
  42. package/src/__tests__/react-query.spec.tsx +582 -0
  43. package/src/__tests__/setup.ts +281 -0
  44. package/src/__tests__/types.spec.ts +134 -0
  45. package/src/__tests__/url-parsing.spec.ts +196 -0
  46. package/src/fetcher.ts +173 -0
  47. package/src/openapi-hooks.ts +193 -0
  48. package/src/openapi-types.d.ts +440 -0
  49. package/src/openapi.json +595 -0
  50. package/src/react-query.ts +341 -0
  51. package/src/types.ts +149 -0
@@ -0,0 +1,341 @@
1
+ import type {
2
+ QueryClient,
3
+ QueryFunctionContext,
4
+ UseInfiniteQueryOptions,
5
+ UseMutationOptions,
6
+ UseQueryOptions,
7
+ } from '@tanstack/react-query';
8
+ import {
9
+ useInfiniteQuery,
10
+ useMutation,
11
+ useQuery,
12
+ useQueryClient,
13
+ } from '@tanstack/react-query';
14
+ import { useMemo } from 'react';
15
+ import { createTypedFetcher } from './fetcher';
16
+ import type {
17
+ ExtractEndpointResponse,
18
+ FetcherOptions,
19
+ FilteredRequestConfig,
20
+ MutationEndpoint,
21
+ QueryEndpoint,
22
+ TypedEndpoint,
23
+ } from './types';
24
+
25
+ export interface TypedQueryClientOptions extends FetcherOptions {
26
+ queryClient?: QueryClient;
27
+ }
28
+
29
+ export class TypedQueryClient<Paths> {
30
+ private fetcher: ReturnType<typeof createTypedFetcher<Paths>>;
31
+ private queryClient?: QueryClient;
32
+
33
+ constructor(options: TypedQueryClientOptions = {}) {
34
+ this.fetcher = createTypedFetcher<Paths>(options);
35
+ this.queryClient = options.queryClient;
36
+ }
37
+
38
+ useQuery<T extends QueryEndpoint<Paths>>(
39
+ endpoint: T,
40
+ config?: FilteredRequestConfig<Paths, T>,
41
+ options?: Omit<
42
+ UseQueryOptions<ExtractEndpointResponse<Paths, T>, Response>,
43
+ 'queryKey' | 'queryFn'
44
+ >,
45
+ ) {
46
+ const queryKey = this.buildQueryKey(endpoint, config);
47
+
48
+ // Memoize the combined options to prevent unnecessary re-renders
49
+ const memoizedOptions = useMemo(
50
+ () => ({
51
+ queryKey,
52
+ queryFn: () => this.fetcher(endpoint, config),
53
+ ...options,
54
+ }),
55
+ // Dependencies: queryKey, endpoint, config, and options
56
+ // Note: We stringify config and options to ensure stable references
57
+ // eslint-disable-next-line react-hooks/exhaustive-deps
58
+ [
59
+ queryKey.join(','),
60
+ endpoint,
61
+ JSON.stringify(config),
62
+ JSON.stringify(options),
63
+ ],
64
+ );
65
+
66
+ return useQuery<ExtractEndpointResponse<Paths, T>, Response>(
67
+ memoizedOptions,
68
+ );
69
+ }
70
+
71
+ useMutation<T extends MutationEndpoint<Paths>>(
72
+ endpoint: T,
73
+ options?: Omit<
74
+ UseMutationOptions<
75
+ ExtractEndpointResponse<Paths, T>,
76
+ Response,
77
+ FilteredRequestConfig<Paths, T>
78
+ >,
79
+ 'mutationFn'
80
+ >,
81
+ ) {
82
+ // Memoize the combined options to prevent unnecessary re-renders
83
+ const memoizedOptions = useMemo(
84
+ () => ({
85
+ mutationFn: (config: FilteredRequestConfig<Paths, T>) =>
86
+ this.fetcher(endpoint, config),
87
+ ...options,
88
+ }),
89
+ // Dependencies: endpoint and options
90
+ // Note: We stringify options to ensure stable reference
91
+ // eslint-disable-next-line react-hooks/exhaustive-deps
92
+ [endpoint, JSON.stringify(options)],
93
+ );
94
+
95
+ return useMutation<
96
+ ExtractEndpointResponse<Paths, T>,
97
+ Response,
98
+ FilteredRequestConfig<Paths, T>
99
+ >(memoizedOptions);
100
+ }
101
+
102
+ useInfiniteQuery<
103
+ T extends QueryEndpoint<Paths>,
104
+ TPageData = ExtractEndpointResponse<Paths, T>,
105
+ TPageParam = unknown,
106
+ >(
107
+ endpoint: T,
108
+ options: Omit<
109
+ UseInfiniteQueryOptions<
110
+ TPageData,
111
+ Response,
112
+ { pages: TPageData[]; pageParams: TPageParam[] },
113
+ unknown[],
114
+ TPageParam
115
+ >,
116
+ 'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'
117
+ > & {
118
+ getNextPageParam: (
119
+ lastPage: TPageData,
120
+ allPages: TPageData[],
121
+ lastPageParam: TPageParam,
122
+ allPageParams: TPageParam[],
123
+ ) => TPageParam | undefined;
124
+ initialPageParam: TPageParam;
125
+ },
126
+ config?: FilteredRequestConfig<Paths, T>,
127
+ ) {
128
+ const queryKey = this.buildQueryKey(endpoint, config);
129
+
130
+ // Memoize the combined options to prevent unnecessary re-renders
131
+ const memoizedOptions = useMemo(
132
+ () => ({
133
+ queryKey,
134
+ queryFn: ({
135
+ pageParam,
136
+ }: QueryFunctionContext<unknown[], TPageParam>) => {
137
+ let mergedConfig = config;
138
+ if (pageParam !== undefined && config) {
139
+ // If pageParam is an object, spread it into query
140
+ const pageQuery =
141
+ typeof pageParam === 'object' ? pageParam : { page: pageParam };
142
+ mergedConfig = {
143
+ ...config,
144
+ query: { ...(config as any).query, ...pageQuery },
145
+ } as any;
146
+ } else if (pageParam !== undefined && !config) {
147
+ // If pageParam is an object, use it directly, otherwise wrap in page property
148
+ const pageQuery =
149
+ typeof pageParam === 'object' ? pageParam : { page: pageParam };
150
+ mergedConfig = { query: pageQuery } as any;
151
+ }
152
+ return this.fetcher(endpoint, mergedConfig) as Promise<TPageData>;
153
+ },
154
+ ...options,
155
+ }),
156
+ // Dependencies: queryKey, endpoint, config, and options
157
+ // Note: We stringify config and options to ensure stable references
158
+ // eslint-disable-next-line react-hooks/exhaustive-deps
159
+ [
160
+ queryKey.join(','),
161
+ endpoint,
162
+ JSON.stringify(config),
163
+ JSON.stringify(options),
164
+ ],
165
+ );
166
+
167
+ return useInfiniteQuery<
168
+ TPageData,
169
+ Response,
170
+ { pages: TPageData[]; pageParams: TPageParam[] },
171
+ unknown[],
172
+ TPageParam
173
+ >(memoizedOptions);
174
+ }
175
+
176
+ buildQueryKey<T extends TypedEndpoint<Paths>>(
177
+ endpoint: T,
178
+ config?: FilteredRequestConfig<Paths, T>,
179
+ ): unknown[] {
180
+ const key: unknown[] = [endpoint];
181
+
182
+ if (config && 'params' in config && config.params) {
183
+ key.push({ params: config.params });
184
+ }
185
+
186
+ if (config && 'query' in config && config.query) {
187
+ key.push({ query: config.query });
188
+ }
189
+
190
+ return key;
191
+ }
192
+
193
+ /**
194
+ * Invalidate queries for a specific endpoint with optional config
195
+ * @param endpoint - The endpoint to invalidate (e.g., 'GET /users')
196
+ * @param config - Optional params/query to match specific queries
197
+ * @returns Promise that resolves when invalidation is complete
198
+ */
199
+ invalidateQueries<T extends QueryEndpoint<Paths>>(
200
+ endpoint: T,
201
+ config?: FilteredRequestConfig<Paths, T>,
202
+ ): Promise<void> {
203
+ const queryClient = this.getQueryClient();
204
+ const queryKey = this.buildQueryKey(endpoint, config);
205
+
206
+ return queryClient.invalidateQueries({
207
+ queryKey,
208
+ exact: !!config, // Use exact matching if config is provided
209
+ });
210
+ }
211
+
212
+ /**
213
+ * Invalidate all queries in the cache
214
+ * @returns Promise that resolves when invalidation is complete
215
+ */
216
+ invalidateAllQueries(): Promise<void> {
217
+ const queryClient = this.getQueryClient();
218
+ return queryClient.invalidateQueries();
219
+ }
220
+
221
+ /**
222
+ * Get the underlying QueryClient instance
223
+ * @returns The QueryClient instance
224
+ */
225
+ getQueryClient(): QueryClient {
226
+ if (this.queryClient) {
227
+ return this.queryClient;
228
+ }
229
+
230
+ // If no query client was provided, try to get it from context
231
+ // This will throw if used outside of QueryClientProvider
232
+ throw new Error(
233
+ 'No QueryClient set, please provide a QueryClient via the queryClient option or ensure you are within a QueryClientProvider',
234
+ );
235
+ }
236
+
237
+ /**
238
+ * Set the QueryClient instance
239
+ * @param queryClient - The QueryClient instance to use
240
+ */
241
+ setQueryClient(queryClient: QueryClient): void {
242
+ this.queryClient = queryClient;
243
+ }
244
+ }
245
+
246
+ export function createTypedQueryClient<Paths>(
247
+ options?: TypedQueryClientOptions,
248
+ ) {
249
+ return new TypedQueryClient<Paths>(options);
250
+ }
251
+
252
+ // Hook exports for convenience
253
+ export function useTypedQuery<Paths, T extends QueryEndpoint<Paths>>(
254
+ client: TypedQueryClient<Paths>,
255
+ endpoint: T,
256
+ config?: FilteredRequestConfig<Paths, T>,
257
+ options?: Omit<
258
+ UseQueryOptions<ExtractEndpointResponse<Paths, T>, Response>,
259
+ 'queryKey' | 'queryFn'
260
+ >,
261
+ ) {
262
+ return client.useQuery(endpoint, config, options);
263
+ }
264
+
265
+ export function useTypedMutation<Paths, T extends MutationEndpoint<Paths>>(
266
+ client: TypedQueryClient<Paths>,
267
+ endpoint: T,
268
+ options?: Omit<
269
+ UseMutationOptions<
270
+ ExtractEndpointResponse<Paths, T>,
271
+ Response,
272
+ FilteredRequestConfig<Paths, T>
273
+ >,
274
+ 'mutationFn'
275
+ >,
276
+ ) {
277
+ return client.useMutation(endpoint, options);
278
+ }
279
+
280
+ export function useTypedInfiniteQuery<
281
+ Paths,
282
+ T extends QueryEndpoint<Paths>,
283
+ TPageData = ExtractEndpointResponse<Paths, T>,
284
+ TPageParam = unknown,
285
+ >(
286
+ client: TypedQueryClient<Paths>,
287
+ endpoint: T,
288
+ options: Omit<
289
+ UseInfiniteQueryOptions<
290
+ TPageData,
291
+ Response,
292
+ { pages: TPageData[]; pageParams: TPageParam[] },
293
+ unknown[],
294
+ TPageParam
295
+ >,
296
+ 'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'
297
+ > & {
298
+ getNextPageParam: (
299
+ lastPage: TPageData,
300
+ allPages: TPageData[],
301
+ lastPageParam: TPageParam,
302
+ allPageParams: TPageParam[],
303
+ ) => TPageParam | undefined;
304
+ initialPageParam: TPageParam;
305
+ },
306
+ config?: FilteredRequestConfig<Paths, T>,
307
+ ) {
308
+ return client.useInfiniteQuery(endpoint, options, config);
309
+ }
310
+
311
+ /**
312
+ * Hook to invalidate queries using the current QueryClient from context
313
+ */
314
+ export function useTypedInvalidateQueries<Paths>(
315
+ client: TypedQueryClient<Paths>,
316
+ ) {
317
+ const queryClient = useQueryClient();
318
+
319
+ return {
320
+ /**
321
+ * Invalidate queries for a specific endpoint
322
+ */
323
+ invalidateQueries: <T extends QueryEndpoint<Paths>>(
324
+ endpoint: T,
325
+ config?: FilteredRequestConfig<Paths, T>,
326
+ ) => {
327
+ const queryKey = client.buildQueryKey(endpoint, config);
328
+ return queryClient.invalidateQueries({
329
+ queryKey,
330
+ exact: !!config,
331
+ });
332
+ },
333
+
334
+ /**
335
+ * Invalidate all queries
336
+ */
337
+ invalidateAllQueries: () => {
338
+ return queryClient.invalidateQueries();
339
+ },
340
+ };
341
+ }
package/src/types.ts ADDED
@@ -0,0 +1,149 @@
1
+ export type OpenAPIRoutes<Paths> = keyof Paths;
2
+
3
+ export type ExtractMethod<
4
+ Paths,
5
+ Route extends OpenAPIRoutes<Paths>,
6
+ > = keyof Paths[Route];
7
+
8
+ export type ExtractPathParams<
9
+ Paths,
10
+ Route extends OpenAPIRoutes<Paths>,
11
+ > = Paths[Route] extends {
12
+ parameters?: { path?: infer P };
13
+ }
14
+ ? P
15
+ : never;
16
+
17
+ export type ExtractQueryParams<
18
+ Paths,
19
+ Route extends OpenAPIRoutes<Paths>,
20
+ Method extends ExtractMethod<Paths, Route>,
21
+ > = Paths[Route][Method] extends { parameters?: { query?: infer Q } }
22
+ ? Q
23
+ : never;
24
+
25
+ export type ExtractRequestBody<
26
+ Paths,
27
+ Route extends OpenAPIRoutes<Paths>,
28
+ Method extends ExtractMethod<Paths, Route>,
29
+ > = Paths[Route][Method] extends {
30
+ requestBody?: { content?: { 'application/json'?: infer B } };
31
+ }
32
+ ? B
33
+ : never;
34
+
35
+ export type ExtractResponse<
36
+ Paths,
37
+ Route extends OpenAPIRoutes<Paths>,
38
+ Method extends ExtractMethod<Paths, Route>,
39
+ > = Paths[Route][Method] extends {
40
+ responses?: { 200?: { content?: { 'application/json'?: infer R } } };
41
+ }
42
+ ? R
43
+ : Paths[Route][Method] extends {
44
+ responses?: { 201?: { content?: { 'application/json'?: infer R } } };
45
+ }
46
+ ? R
47
+ : never;
48
+
49
+ export type RequestConfig<
50
+ Paths,
51
+ Route extends OpenAPIRoutes<Paths>,
52
+ Method extends ExtractMethod<Paths, Route>,
53
+ > = {
54
+ params?: ExtractPathParams<Paths, Route>;
55
+ query?: ExtractQueryParams<Paths, Route, Method>;
56
+ body?: ExtractRequestBody<Paths, Route, Method>;
57
+ headers?: Record<string, string>;
58
+ };
59
+
60
+ export type EndpointString = `${Uppercase<string>} ${string}`;
61
+
62
+ // Filter out methods that are never to avoid showing them in autocomplete
63
+ // This handles both explicit never and optional never (?: never)
64
+ type FilterNeverMethods<T> = {
65
+ [K in keyof T as T[K] extends never | undefined
66
+ ? never
67
+ : K]: T[K] extends undefined ? never : T[K];
68
+ };
69
+
70
+ // Generate all valid endpoint strings from OpenAPI paths
71
+ export type ValidEndpoint<Paths> = {
72
+ [Route in keyof Paths]: {
73
+ [Method in keyof FilterNeverMethods<Paths[Route]>]: `${Uppercase<
74
+ string & Method
75
+ >} ${string & Route}`;
76
+ }[keyof FilterNeverMethods<Paths[Route]>];
77
+ }[keyof Paths];
78
+
79
+ // Helper type to get autocomplete for endpoint strings
80
+ export type TypedEndpoint<Paths> = ValidEndpoint<Paths> extends infer E
81
+ ? E extends string
82
+ ? E
83
+ : never
84
+ : never;
85
+
86
+ // Filter endpoints by HTTP method
87
+ export type FilterEndpointByMethod<
88
+ Paths,
89
+ Method extends string,
90
+ > = ValidEndpoint<Paths> extends infer E
91
+ ? E extends `${Method} ${string}`
92
+ ? E
93
+ : never
94
+ : never;
95
+
96
+ // Query endpoints (GET only)
97
+ export type QueryEndpoint<Paths> = FilterEndpointByMethod<Paths, 'GET'>;
98
+
99
+ // Mutation endpoints (POST, PATCH, PUT, DELETE)
100
+ export type MutationEndpoint<Paths> =
101
+ | FilterEndpointByMethod<Paths, 'POST'>
102
+ | FilterEndpointByMethod<Paths, 'PATCH'>
103
+ | FilterEndpointByMethod<Paths, 'PUT'>
104
+ | FilterEndpointByMethod<Paths, 'DELETE'>;
105
+
106
+ export type ParseEndpoint<T extends EndpointString> =
107
+ T extends `${infer Method} ${infer Route}`
108
+ ? { method: Lowercase<Method>; route: Route }
109
+ : never;
110
+
111
+ export type ExtractEndpointResponse<
112
+ Paths,
113
+ T extends EndpointString,
114
+ > = T extends `${infer Method} ${infer Route}`
115
+ ? Route extends OpenAPIRoutes<Paths>
116
+ ? Lowercase<Method> extends ExtractMethod<Paths, Route>
117
+ ? ExtractResponse<Paths, Route, Lowercase<Method>>
118
+ : never
119
+ : never
120
+ : never;
121
+
122
+ export type ExtractEndpointConfig<
123
+ Paths,
124
+ T extends EndpointString,
125
+ > = T extends `${infer Method} ${infer Route}`
126
+ ? Route extends OpenAPIRoutes<Paths>
127
+ ? Lowercase<Method> extends ExtractMethod<Paths, Route>
128
+ ? RequestConfig<Paths, Route, Lowercase<Method>>
129
+ : never
130
+ : never
131
+ : never;
132
+
133
+ export type FilteredRequestConfig<Paths, T extends EndpointString> = {
134
+ [K in keyof ExtractEndpointConfig<Paths, T> as ExtractEndpointConfig<
135
+ Paths,
136
+ T
137
+ >[K] extends never | undefined
138
+ ? never
139
+ : K]: ExtractEndpointConfig<Paths, T>[K];
140
+ };
141
+
142
+ export interface FetcherOptions {
143
+ baseURL?: string;
144
+ headers?: Record<string, string>;
145
+ onRequest?: (config: RequestInit) => RequestInit | Promise<RequestInit>;
146
+ onResponse?: (response: Response) => Response | Promise<Response>;
147
+ onError?: (error: Error) => void | Promise<void>;
148
+ fetch?: typeof fetch;
149
+ }