-
-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathreact.ts
More file actions
761 lines (671 loc) · 31.2 KB
/
react.ts
File metadata and controls
761 lines (671 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
import {
useInfiniteQuery,
useMutation,
useQuery,
useQueryClient,
useSuspenseInfiniteQuery,
useSuspenseQuery,
type DefaultError,
type InfiniteData,
type QueryKey,
type UseInfiniteQueryOptions,
type UseInfiniteQueryResult,
type UseMutationOptions,
type UseMutationResult,
type UseQueryOptions,
type UseQueryResult,
type UseSuspenseInfiniteQueryOptions,
type UseSuspenseInfiniteQueryResult,
type UseSuspenseQueryOptions,
type UseSuspenseQueryResult,
} from '@tanstack/react-query';
import { createInvalidator, createOptimisticUpdater, DEFAULT_QUERY_ENDPOINT, type InferExtResult, type InferOptions, type InferSchema } from '@zenstackhq/client-helpers';
import { fetcher, makeUrl, marshal } from '@zenstackhq/client-helpers/fetch';
import { lowerCaseFirst } from '@zenstackhq/common-helpers';
import type {
AggregateArgs,
AggregateResult,
BatchResult,
ClientContract,
CountArgs,
CountResult,
CreateArgs,
CreateManyAndReturnArgs,
CreateManyArgs,
DeleteArgs,
DeleteManyArgs,
ExistsArgs,
ExtResultBase,
FindFirstArgs,
FindManyArgs,
FindUniqueArgs,
GetProcedure,
GetProcedureNames,
GetSlicedModels,
GetSlicedProcedures,
GroupByArgs,
GroupByResult,
ProcedureEnvelope,
QueryOptions,
SelectSubset,
SimplifiedPlainResult,
SimplifiedResult,
Subset,
UpdateArgs,
UpdateManyAndReturnArgs,
UpdateManyArgs,
UpsertArgs,
} from '@zenstackhq/orm';
import type { GetModels, SchemaDef } from '@zenstackhq/schema';
import { createContext, useContext } from 'react';
import { getAllQueries, invalidateQueriesMatchingPredicate } from './common/client.js';
import { CUSTOM_PROC_ROUTE_NAME } from './common/constants.js';
import { getQueryKey } from './common/query-key.js';
import type {
ExtraMutationOptions,
ExtraQueryOptions,
ProcedureReturn,
QueryContext,
TrimSlicedOperations,
WithOptimistic,
} from './common/types.js';
export type { FetchFn } from '@zenstackhq/client-helpers/fetch';
export type { InferExtResult, InferOptions, InferSchema } from '@zenstackhq/client-helpers';
export type { SchemaDef } from '@zenstackhq/schema';
type ProcedureHookFn<
Schema extends SchemaDef,
ProcName extends GetProcedureNames<Schema>,
Options,
Result,
Input = ProcedureEnvelope<Schema, ProcName>,
> = { args: undefined } extends Input
? (input?: Input, options?: Options) => Result
: (input: Input, options?: Options) => Result;
/**
* React context for query settings.
*/
export const QuerySettingsContext = createContext<QueryContext>({
endpoint: DEFAULT_QUERY_ENDPOINT,
fetch: undefined,
});
/**
* React context provider for configuring query settings.
*/
export const QuerySettingsProvider = QuerySettingsContext.Provider;
/**
* React context provider for configuring query settings.
*
* @deprecated Use {@link QuerySettingsProvider} instead.
*/
export const Provider = QuerySettingsProvider;
function useHooksContext() {
const { endpoint, ...rest } = useContext(QuerySettingsContext);
return { endpoint: endpoint ?? DEFAULT_QUERY_ENDPOINT, ...rest };
}
export type ModelQueryOptions<T> = Omit<UseQueryOptions<T, DefaultError>, 'queryKey'> & ExtraQueryOptions;
export type ModelQueryResult<T> = UseQueryResult<WithOptimistic<T>, DefaultError> & { queryKey: QueryKey };
export type ModelSuspenseQueryOptions<T> = Omit<UseSuspenseQueryOptions<T, DefaultError>, 'queryKey'> &
ExtraQueryOptions;
export type ModelSuspenseQueryResult<T> = UseSuspenseQueryResult<WithOptimistic<T>, DefaultError> & {
queryKey: QueryKey;
};
export type ModelInfiniteQueryOptions<T, TPageParam = unknown> = Omit<
UseInfiniteQueryOptions<T, DefaultError, InfiniteData<T, TPageParam>, QueryKey, TPageParam>,
'queryKey' | 'initialPageParam'
>;
export type ModelInfiniteQueryResult<T> = UseInfiniteQueryResult<T, DefaultError> & { queryKey: QueryKey };
export type ModelSuspenseInfiniteQueryOptions<T, TPageParam = unknown> = Omit<
UseSuspenseInfiniteQueryOptions<T, DefaultError, InfiniteData<T, TPageParam>, QueryKey, TPageParam>,
'queryKey' | 'initialPageParam'
>;
export type ModelSuspenseInfiniteQueryResult<T> = UseSuspenseInfiniteQueryResult<T, DefaultError> & {
queryKey: QueryKey;
};
export type ModelMutationOptions<T, TArgs> = Omit<UseMutationOptions<T, DefaultError, TArgs>, 'mutationFn'> &
ExtraMutationOptions;
export type ModelMutationResult<T, TArgs> = UseMutationResult<T, DefaultError, TArgs>;
export type ModelMutationModelResult<
Schema extends SchemaDef,
Model extends GetModels<Schema>,
TArgs,
Array extends boolean = false,
Options extends QueryOptions<Schema> = QueryOptions<Schema>,
ExtResult extends ExtResultBase<Schema> = {},
> = Omit<ModelMutationResult<SimplifiedResult<Schema, Model, TArgs, Options, false, Array, ExtResult>, TArgs>, 'mutateAsync'> & {
mutateAsync<T extends TArgs>(
args: T,
options?: ModelMutationOptions<SimplifiedResult<Schema, Model, T, Options, false, Array, ExtResult>, T>,
): Promise<SimplifiedResult<Schema, Model, T, Options, false, Array, ExtResult>>;
};
export type ClientHooks<
Schema extends SchemaDef,
Options extends QueryOptions<Schema> = QueryOptions<Schema>,
ExtResult extends ExtResultBase<Schema> = {},
> = {
[Model in GetSlicedModels<Schema, Options> as `${Uncapitalize<Model>}`]: ModelQueryHooks<Schema, Model, Options, ExtResult>;
} & ProcedureHooks<Schema, Options>;
type ProcedureHookGroup<Schema extends SchemaDef, Options extends QueryOptions<Schema>> = {
[Name in GetSlicedProcedures<Schema, Options>]: GetProcedure<Schema, Name> extends { mutation: true }
? {
useMutation(
options?: Omit<
UseMutationOptions<ProcedureReturn<Schema, Name>, DefaultError, ProcedureEnvelope<Schema, Name>>,
'mutationFn'
> &
QueryContext,
): UseMutationResult<ProcedureReturn<Schema, Name>, DefaultError, ProcedureEnvelope<Schema, Name>>;
}
: {
useQuery: ProcedureHookFn<
Schema,
Name,
Omit<ModelQueryOptions<ProcedureReturn<Schema, Name>>, 'optimisticUpdate'>,
UseQueryResult<ProcedureReturn<Schema, Name>, DefaultError> & { queryKey: QueryKey }
>;
useSuspenseQuery: ProcedureHookFn<
Schema,
Name,
Omit<ModelSuspenseQueryOptions<ProcedureReturn<Schema, Name>>, 'optimisticUpdate'>,
UseSuspenseQueryResult<ProcedureReturn<Schema, Name>, DefaultError> & { queryKey: QueryKey }
>;
// Infinite queries for procedures are currently disabled, will add back later if needed
//
// useInfiniteQuery: ProcedureHookFn<
// Schema,
// Name,
// ModelInfiniteQueryOptions<ProcedureReturn<Schema, Name>>,
// ModelInfiniteQueryResult<InfiniteData<ProcedureReturn<Schema, Name>>>
// >;
// useSuspenseInfiniteQuery: ProcedureHookFn<
// Schema,
// Name,
// ModelSuspenseInfiniteQueryOptions<ProcedureReturn<Schema, Name>>,
// ModelSuspenseInfiniteQueryResult<InfiniteData<ProcedureReturn<Schema, Name>>>
// >;
};
};
export type ProcedureHooks<Schema extends SchemaDef, Options extends QueryOptions<Schema>> =
Schema['procedures'] extends Record<string, any>
? {
/**
* Custom procedures.
*/
$procs: ProcedureHookGroup<Schema, Options>;
}
: Record<never, never>;
// Note that we can potentially use TypeScript's mapped type to directly map from ORM contract, but that seems
// to significantly slow down tsc performance ...
export type ModelQueryHooks<
Schema extends SchemaDef,
Model extends GetModels<Schema>,
Options extends QueryOptions<Schema> = QueryOptions<Schema>,
ExtResult extends ExtResultBase<Schema> = {},
> = TrimSlicedOperations<
Schema,
Model,
Options,
{
useFindUnique<T extends FindUniqueArgs<Schema, Model, Options, {}, ExtResult>>(
args: SelectSubset<T, FindUniqueArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>,
): ModelQueryResult<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
useSuspenseFindUnique<T extends FindUniqueArgs<Schema, Model, Options, {}, ExtResult>>(
args: SelectSubset<T, FindUniqueArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelSuspenseQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>,
): ModelSuspenseQueryResult<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
useFindFirst<T extends FindFirstArgs<Schema, Model, Options, {}, ExtResult>>(
args?: SelectSubset<T, FindFirstArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>,
): ModelQueryResult<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
useSuspenseFindFirst<T extends FindFirstArgs<Schema, Model, Options, {}, ExtResult>>(
args?: SelectSubset<T, FindFirstArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelSuspenseQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>,
): ModelSuspenseQueryResult<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
useExists<T extends ExistsArgs<Schema, Model, Options>>(
args?: Subset<T, ExistsArgs<Schema, Model, Options>>,
options?: ModelQueryOptions<boolean>,
): ModelQueryResult<boolean>;
useFindMany<T extends FindManyArgs<Schema, Model, Options, {}, ExtResult>>(
args?: SelectSubset<T, FindManyArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>,
): ModelQueryResult<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
useSuspenseFindMany<T extends FindManyArgs<Schema, Model, Options, {}, ExtResult>>(
args?: SelectSubset<T, FindManyArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelSuspenseQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>,
): ModelSuspenseQueryResult<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
useInfiniteFindMany<T extends FindManyArgs<Schema, Model, Options, {}, ExtResult>, TPageParam = unknown>(
args?: SelectSubset<T, FindManyArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelInfiniteQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[], TPageParam>,
): ModelInfiniteQueryResult<InfiniteData<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[], TPageParam>>;
useSuspenseInfiniteFindMany<T extends FindManyArgs<Schema, Model, Options, {}, ExtResult>, TPageParam = unknown>(
args?: SelectSubset<T, FindManyArgs<Schema, Model, Options, {}, ExtResult>>,
options?: ModelSuspenseInfiniteQueryOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[], TPageParam>,
): ModelSuspenseInfiniteQueryResult<InfiniteData<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[], TPageParam>>;
useCreate<T extends CreateArgs<Schema, Model, Options, {}, ExtResult>>(
options?: ModelMutationOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>, T>,
): ModelMutationModelResult<Schema, Model, T, false, Options, ExtResult>;
useCreateMany<T extends CreateManyArgs<Schema, Model>>(
options?: ModelMutationOptions<BatchResult, T>,
): ModelMutationResult<BatchResult, T>;
useCreateManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model, Options, {}, ExtResult>>(
options?: ModelMutationOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[], T>,
): ModelMutationModelResult<Schema, Model, T, true, Options, ExtResult>;
useUpdate<T extends UpdateArgs<Schema, Model, Options, {}, ExtResult>>(
options?: ModelMutationOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>, T>,
): ModelMutationModelResult<Schema, Model, T, false, Options, ExtResult>;
useUpdateMany<T extends UpdateManyArgs<Schema, Model, Options>>(
options?: ModelMutationOptions<BatchResult, T>,
): ModelMutationResult<BatchResult, T>;
useUpdateManyAndReturn<T extends UpdateManyAndReturnArgs<Schema, Model, Options, {}, ExtResult>>(
options?: ModelMutationOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[], T>,
): ModelMutationModelResult<Schema, Model, T, true, Options, ExtResult>;
useUpsert<T extends UpsertArgs<Schema, Model, Options, {}, ExtResult>>(
options?: ModelMutationOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>, T>,
): ModelMutationModelResult<Schema, Model, T, false, Options, ExtResult>;
useDelete<T extends DeleteArgs<Schema, Model, Options, {}, ExtResult>>(
options?: ModelMutationOptions<SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>, T>,
): ModelMutationModelResult<Schema, Model, T, false, Options, ExtResult>;
useDeleteMany<T extends DeleteManyArgs<Schema, Model, Options>>(
options?: ModelMutationOptions<BatchResult, T>,
): ModelMutationResult<BatchResult, T>;
useCount<T extends CountArgs<Schema, Model, Options>>(
args?: Subset<T, CountArgs<Schema, Model, Options>>,
options?: ModelQueryOptions<CountResult<Schema, Model, T>>,
): ModelQueryResult<CountResult<Schema, Model, T>>;
useSuspenseCount<T extends CountArgs<Schema, Model, Options>>(
args?: Subset<T, CountArgs<Schema, Model, Options>>,
options?: ModelSuspenseQueryOptions<CountResult<Schema, Model, T>>,
): ModelSuspenseQueryResult<CountResult<Schema, Model, T>>;
useAggregate<T extends AggregateArgs<Schema, Model, Options>>(
args: Subset<T, AggregateArgs<Schema, Model, Options>>,
options?: ModelQueryOptions<AggregateResult<Schema, Model, T>>,
): ModelQueryResult<AggregateResult<Schema, Model, T>>;
useSuspenseAggregate<T extends AggregateArgs<Schema, Model, Options>>(
args: Subset<T, AggregateArgs<Schema, Model, Options>>,
options?: ModelSuspenseQueryOptions<AggregateResult<Schema, Model, T>>,
): ModelSuspenseQueryResult<AggregateResult<Schema, Model, T>>;
useGroupBy<T extends GroupByArgs<Schema, Model, Options>>(
args: Subset<T, GroupByArgs<Schema, Model, Options>>,
options?: ModelQueryOptions<GroupByResult<Schema, Model, T>>,
): ModelQueryResult<GroupByResult<Schema, Model, T>>;
useSuspenseGroupBy<T extends GroupByArgs<Schema, Model, Options>>(
args: Subset<T, GroupByArgs<Schema, Model, Options>>,
options?: ModelSuspenseQueryOptions<GroupByResult<Schema, Model, T>>,
): ModelSuspenseQueryResult<GroupByResult<Schema, Model, T>>;
}
>;
/**
* Gets data query hooks for all models in the schema.
*
* Accepts either a raw `SchemaDef` or a `ClientContract` type (e.g. `typeof db`) as the generic parameter.
* When a `ClientContract` type is provided, computed fields from plugins are reflected in the result types.
*
* @example
* ```typescript
* // Basic usage with schema
* const client = useClientQueries(schema)
*
* // With server client type for computed field support
* import type { DbType } from '~/server/db'
* const client = useClientQueries<DbType>(schema)
* ```
*
* @param schema The schema.
* @param options Options for all queries originated from this hook.
*/
export function useClientQueries<
SchemaOrClient extends SchemaDef | ClientContract<any, any, any, any, any>,
>(
schema: InferSchema<SchemaOrClient>,
options?: QueryContext,
): ClientHooks<InferSchema<SchemaOrClient>, InferOptions<SchemaOrClient, InferSchema<SchemaOrClient>>, InferExtResult<SchemaOrClient> extends ExtResultBase<InferSchema<SchemaOrClient>> ? InferExtResult<SchemaOrClient> : {}> {
const result = Object.keys(schema.models).reduce(
(acc, model) => {
(acc as any)[lowerCaseFirst(model)] = useModelQueries(
schema as any,
model as any,
options,
);
return acc;
},
{} as any,
);
const procedures = (schema as any).procedures as Record<string, { mutation?: boolean }> | undefined;
if (procedures) {
const buildProcedureHooks = () => {
return Object.keys(procedures).reduce((acc, name) => {
const procDef = procedures[name];
if (procDef?.mutation) {
acc[name] = {
useMutation: (hookOptions?: any) =>
useInternalMutation(schema, CUSTOM_PROC_ROUTE_NAME, 'POST', name, {
...options,
...hookOptions,
}),
};
} else {
acc[name] = {
useQuery: (args?: any, hookOptions?: any) =>
useInternalQuery(schema, CUSTOM_PROC_ROUTE_NAME, name, args, {
...options,
...hookOptions,
}),
useSuspenseQuery: (args?: any, hookOptions?: any) =>
useInternalSuspenseQuery(schema, CUSTOM_PROC_ROUTE_NAME, name, args, {
...options,
...hookOptions,
}),
useInfiniteQuery: (args?: any, hookOptions?: any) =>
useInternalInfiniteQuery(schema, CUSTOM_PROC_ROUTE_NAME, name, args, {
...options,
...hookOptions,
}),
useSuspenseInfiniteQuery: (args?: any, hookOptions?: any) =>
useInternalSuspenseInfiniteQuery(schema, CUSTOM_PROC_ROUTE_NAME, name, args, {
...options,
...hookOptions,
}),
};
}
return acc;
}, {} as any);
};
(result as any).$procs = buildProcedureHooks();
}
return result;
}
/**
* Gets data query hooks for a specific model in the schema.
*/
export function useModelQueries<
Schema extends SchemaDef,
Model extends GetModels<Schema>,
Options extends QueryOptions<Schema>,
ExtResult extends ExtResultBase<Schema> = {},
>(schema: Schema, model: Model, rootOptions?: QueryContext): ModelQueryHooks<Schema, Model, Options, ExtResult> {
const modelDef = Object.values(schema.models).find((m) => m.name.toLowerCase() === model.toLowerCase());
if (!modelDef) {
throw new Error(`Model "${model}" not found in schema`);
}
const modelName = modelDef.name;
return {
useFindUnique: (args: any, options?: any) => {
return useInternalQuery(schema, modelName, 'findUnique', args, { ...rootOptions, ...options });
},
useSuspenseFindUnique: (args: any, options?: any) => {
return useInternalSuspenseQuery(schema, modelName, 'findUnique', args, { ...rootOptions, ...options });
},
useFindFirst: (args: any, options?: any) => {
return useInternalQuery(schema, modelName, 'findFirst', args, { ...rootOptions, ...options });
},
useSuspenseFindFirst: (args: any, options?: any) => {
return useInternalSuspenseQuery(schema, modelName, 'findFirst', args, { ...rootOptions, ...options });
},
useExists: (args: any, options?: any) => {
return useInternalQuery(schema, modelName, 'exists', args, { ...rootOptions, ...options });
},
useFindMany: (args: any, options?: any) => {
return useInternalQuery(schema, modelName, 'findMany', args, { ...rootOptions, ...options });
},
useSuspenseFindMany: (args: any, options?: any) => {
return useInternalSuspenseQuery(schema, modelName, 'findMany', args, { ...rootOptions, ...options });
},
useInfiniteFindMany: (args: any, options?: any) => {
return useInternalInfiniteQuery(schema, modelName, 'findMany', args, { ...rootOptions, ...options });
},
useSuspenseInfiniteFindMany: (args: any, options?: any) => {
return useInternalSuspenseInfiniteQuery(schema, modelName, 'findMany', args, {
...rootOptions,
...options,
});
},
useCreate: (options?: any) => {
return useInternalMutation(schema, modelName, 'POST', 'create', { ...rootOptions, ...options });
},
useCreateMany: (options?: any) => {
return useInternalMutation(schema, modelName, 'POST', 'createMany', { ...rootOptions, ...options });
},
useCreateManyAndReturn: (options?: any) => {
return useInternalMutation(schema, modelName, 'POST', 'createManyAndReturn', {
...rootOptions,
...options,
});
},
useUpdate: (options?: any) => {
return useInternalMutation(schema, modelName, 'PUT', 'update', { ...rootOptions, ...options });
},
useUpdateMany: (options?: any) => {
return useInternalMutation(schema, modelName, 'PUT', 'updateMany', { ...rootOptions, ...options });
},
useUpdateManyAndReturn: (options?: any) => {
return useInternalMutation(schema, modelName, 'PUT', 'updateManyAndReturn', { ...rootOptions, ...options });
},
useUpsert: (options?: any) => {
return useInternalMutation(schema, modelName, 'POST', 'upsert', { ...rootOptions, ...options });
},
useDelete: (options?: any) => {
return useInternalMutation(schema, modelName, 'DELETE', 'delete', { ...rootOptions, ...options });
},
useDeleteMany: (options?: any) => {
return useInternalMutation(schema, modelName, 'DELETE', 'deleteMany', { ...rootOptions, ...options });
},
useCount: (args: any, options?: any) => {
return useInternalQuery(schema, modelName, 'count', args, { ...rootOptions, ...options });
},
useSuspenseCount: (args: any, options?: any) => {
return useInternalSuspenseQuery(schema, modelName, 'count', args, { ...rootOptions, ...options });
},
useAggregate: (args: any, options?: any) => {
return useInternalQuery(schema, modelName, 'aggregate', args, { ...rootOptions, ...options });
},
useSuspenseAggregate: (args: any, options?: any) => {
return useInternalSuspenseQuery(schema, modelName, 'aggregate', args, { ...rootOptions, ...options });
},
useGroupBy: (args: any, options?: any) => {
return useInternalQuery(schema, modelName, 'groupBy', args, { ...rootOptions, ...options });
},
useSuspenseGroupBy: (args: any, options?: any) => {
return useInternalSuspenseQuery(schema, modelName, 'groupBy', args, { ...rootOptions, ...options });
},
} as ModelQueryHooks<Schema, Model, Options, ExtResult>;
}
export function useInternalQuery<TQueryFnData, TData>(
_schema: SchemaDef,
model: string,
operation: string,
args?: unknown,
options?: Omit<UseQueryOptions<TQueryFnData, DefaultError, TData>, 'queryKey'> & ExtraQueryOptions,
) {
const { endpoint, fetch } = useFetchOptions(options);
const reqUrl = makeUrl(endpoint, model, operation, args);
const queryKey = getQueryKey(model, operation, args, {
infinite: false,
optimisticUpdate: options?.optimisticUpdate !== false,
});
return {
queryKey,
...useQuery({
queryKey,
queryFn: ({ signal }) => fetcher<TQueryFnData>(reqUrl, { signal }, fetch),
...options,
}),
};
}
export function useInternalSuspenseQuery<TQueryFnData, TData>(
_schema: SchemaDef,
model: string,
operation: string,
args?: unknown,
options?: Omit<UseSuspenseQueryOptions<TQueryFnData, DefaultError, TData>, 'queryKey'> & ExtraQueryOptions,
) {
const { endpoint, fetch } = useFetchOptions(options);
const reqUrl = makeUrl(endpoint, model, operation, args);
const queryKey = getQueryKey(model, operation, args, {
infinite: false,
optimisticUpdate: options?.optimisticUpdate !== false,
});
return {
queryKey,
...useSuspenseQuery({
queryKey,
queryFn: ({ signal }) => fetcher<TQueryFnData>(reqUrl, { signal }, fetch),
...options,
}),
};
}
export function useInternalInfiniteQuery<TQueryFnData, TData, TPageParam = unknown>(
_schema: SchemaDef,
model: string,
operation: string,
args: unknown,
options:
| (Omit<
UseInfiniteQueryOptions<TQueryFnData, DefaultError, InfiniteData<TData, TPageParam>, QueryKey, TPageParam>,
'queryKey' | 'initialPageParam'
> &
QueryContext)
| undefined,
) {
options = options ?? { getNextPageParam: () => undefined };
const { endpoint, fetch } = useFetchOptions(options);
const queryKey = getQueryKey(model, operation, args, { infinite: true, optimisticUpdate: false });
return {
queryKey,
...useInfiniteQuery({
queryKey,
queryFn: ({ pageParam, signal }) => {
return fetcher<TQueryFnData>(makeUrl(endpoint, model, operation, pageParam ?? args), { signal }, fetch);
},
initialPageParam: args as TPageParam,
...options,
}),
};
}
export function useInternalSuspenseInfiniteQuery<TQueryFnData, TData, TPageParam = unknown>(
_schema: SchemaDef,
model: string,
operation: string,
args: unknown,
options: Omit<
UseSuspenseInfiniteQueryOptions<TQueryFnData, DefaultError, InfiniteData<TData, TPageParam>, QueryKey, TPageParam> & QueryContext,
'queryKey' | 'initialPageParam'
>,
) {
const { endpoint, fetch } = useFetchOptions(options);
const queryKey = getQueryKey(model, operation, args, { infinite: true, optimisticUpdate: false });
return {
queryKey,
...useSuspenseInfiniteQuery({
queryKey,
queryFn: ({ pageParam, signal }) => {
return fetcher<TQueryFnData>(makeUrl(endpoint, model, operation, pageParam ?? args), { signal }, fetch);
},
initialPageParam: args as TPageParam,
...options,
}),
};
}
/**
* Creates a react-query mutation
*
* @private
*
* @param model The name of the model under mutation.
* @param method The HTTP method.
* @param operation The mutation operation (e.g. `create`).
* @param options The react-query options.
* @param checkReadBack Whether to check for read back errors and return undefined if found.
*/
export function useInternalMutation<TArgs, R = any>(
schema: SchemaDef,
model: string,
method: 'POST' | 'PUT' | 'DELETE',
operation: string,
options?: Omit<UseMutationOptions<R, DefaultError, TArgs>, 'mutationFn'> & ExtraMutationOptions,
) {
const { endpoint, fetch, logging } = useFetchOptions(options);
const queryClient = useQueryClient();
const mutationFn = (data: any) => {
const reqUrl =
method === 'DELETE' ? makeUrl(endpoint, model, operation, data) : makeUrl(endpoint, model, operation);
const fetchInit: RequestInit = {
method,
...(method !== 'DELETE' && {
headers: {
'content-type': 'application/json',
},
body: marshal(data),
}),
};
return fetcher<R>(reqUrl, fetchInit, fetch) as Promise<R>;
};
const finalOptions = { ...options, mutationFn };
if (model !== CUSTOM_PROC_ROUTE_NAME) {
// not a custom procedure, set up optimistic update and invalidation
const invalidateQueries = options?.invalidateQueries !== false;
const optimisticUpdate = !!options?.optimisticUpdate;
if (!optimisticUpdate) {
// if optimistic update is not enabled, invalidate related queries on success
if (invalidateQueries) {
const invalidator = createInvalidator(
model,
operation,
schema,
(predicate) => invalidateQueriesMatchingPredicate(queryClient, predicate),
logging,
);
const origOnSuccess = finalOptions.onSuccess;
finalOptions.onSuccess = async (...args) => {
// execute invalidator prior to user-provided onSuccess
await invalidator(...args);
// call user-provided onSuccess
await origOnSuccess?.(...args);
};
}
} else {
// schedule optimistic update on mutate
const optimisticUpdater = createOptimisticUpdater(
model,
operation,
schema,
{ optimisticDataProvider: finalOptions.optimisticDataProvider },
() => getAllQueries(queryClient),
logging,
);
const origOnMutate = finalOptions.onMutate;
finalOptions.onMutate = async (...args) => {
// execute optimistic update
await optimisticUpdater(...args);
// call user-provided onMutate
return origOnMutate?.(...args);
};
if (invalidateQueries) {
// invalidate related queries on settled (success or error)
const invalidator = createInvalidator(
model,
operation,
schema,
(predicate) => invalidateQueriesMatchingPredicate(queryClient, predicate),
logging,
);
const origOnSettled = finalOptions.onSettled;
finalOptions.onSettled = async (...args) => {
// execute invalidator prior to user-provided onSettled
await invalidator(...args);
// call user-provided onSettled
return origOnSettled?.(...args);
};
}
}
}
return useMutation(finalOptions);
}
function useFetchOptions(options: QueryContext | undefined) {
const { endpoint, fetch, logging } = useHooksContext();
// options take precedence over context
return {
endpoint: options?.endpoint ?? endpoint,
fetch: options?.fetch ?? fetch,
logging: options?.logging ?? logging,
};
}