-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathindex.ts
552 lines (499 loc) · 17 KB
/
index.ts
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { deserialize, serialize } from '@zenstackhq/runtime/browser';
import {
applyMutation,
getMutatedModels,
getReadModels,
type ModelMeta,
type PrismaWriteActionType,
} from '@zenstackhq/runtime/cross';
import { lowerCaseFirst } from 'lower-case-first';
import { createContext, useContext } from 'react';
import type { Cache, Fetcher, SWRConfiguration, SWRResponse } from 'swr';
import useSWR, { useSWRConfig } from 'swr';
import { ScopedMutator } from 'swr/_internal';
import useSWRInfinite, {
unstable_serialize,
type SWRInfiniteConfiguration,
type SWRInfiniteFetcher,
type SWRInfiniteResponse,
} from 'swr/infinite';
import useSWRMutation, { type SWRMutationConfiguration } from 'swr/mutation';
export * from './prisma-types';
/**
* Function signature for `fetch`.
*/
export type FetchFn = (url: string, options?: RequestInit) => Promise<Response>;
/**
* Context type for configuring react hooks.
*/
export type RequestHandlerContext = {
/**
* The endpoint to use for the queries.
*/
endpoint?: string;
/**
* A custom fetch function for sending the HTTP requests.
*/
fetch?: FetchFn;
/**
* If logging is enabled.
*/
logging?: boolean;
};
const DEFAULT_QUERY_ENDPOINT = '/api/model';
/**
* Context for configuring react hooks.
*/
export const RequestHandlerContext = createContext<RequestHandlerContext>({
endpoint: DEFAULT_QUERY_ENDPOINT,
fetch: undefined,
});
/**
* Context provider.
*/
export const Provider = RequestHandlerContext.Provider;
/**
* Hooks context.
*/
export function useHooksContext() {
const { endpoint, ...rest } = useContext(RequestHandlerContext);
return { endpoint: endpoint ?? DEFAULT_QUERY_ENDPOINT, ...rest };
}
/**
* Regular query options.
*/
export type QueryOptions<Result, Error = unknown> = {
/**
* Disable data fetching
*/
disabled?: boolean;
/**
* Whether to enable automatic optimistic update. Defaults to `true`.
*/
optimisticUpdate?: boolean;
} & Omit<SWRConfiguration<Result, Error, Fetcher<Result>>, 'fetcher'>;
/**
* Infinite query options.
*/
export type InfiniteQueryOptions<Result, Error = unknown> = {
/**
* Disable data fetching
*/
disabled?: boolean;
} & Omit<SWRInfiniteConfiguration<Result, Error, SWRInfiniteFetcher<Result>>, 'fetcher'>;
const QUERY_KEY_PREFIX = 'zenstack:query';
const MUTATION_KEY_PREFIX = 'zenstack:mutation';
type QueryKey = {
prefix: typeof QUERY_KEY_PREFIX;
model: string;
operation: string;
args?: unknown;
infinite?: boolean;
optimisticUpdate?: boolean;
};
/**
* Result of optimistic data provider.
*/
export type OptimisticDataProviderResult = {
/**
* Kind of the result.
* - Update: use the `data` field to update the query cache.
* - Skip: skip the optimistic update for this query.
* - ProceedDefault: proceed with the default optimistic update.
*/
kind: 'Update' | 'Skip' | 'ProceedDefault';
/**
* Data to update the query cache. Only applicable if `kind` is 'Update'.
*
* If the data is an object with fields updated, it should have a `$optimistic`
* field set to `true`. If it's an array and an element object is created or updated,
* the element should have a `$optimistic` field set to `true`.
*/
data?: any;
};
/**
* Optimistic data provider.
*
* @param args Arguments.
* @param args.queryModel The model of the query.
* @param args.queryOperation The operation of the query, `findMany`, `count`, etc.
* @param args.queryArgs The arguments of the query.
* @param args.currentData The current cache data for the query.
* @param args.mutationArgs The arguments of the mutation.
*/
export type OptimisticDataProvider = (args: {
queryModel: string;
queryOperation: string;
queryArgs: any;
currentData: any;
mutationArgs: any;
}) => OptimisticDataProviderResult | Promise<OptimisticDataProviderResult>;
/**
* Mutation options.
*/
export type MutationOptions<Result, Error, Args> = {
/**
* Whether to automatically optimistic-update queries potentially impacted. Defaults to `false`.
*/
optimisticUpdate?: boolean;
/**
* A callback for computing optimistic update data for each query cache entry.
*/
optimisticDataProvider?: OptimisticDataProvider;
} & Omit<SWRMutationConfiguration<Result, Error, string, Args>, 'fetcher'>;
/**
* Computes query key for the given model, operation, query args, and options.
*/
export function getQueryKey(
model: string,
operation: string,
args?: unknown,
infinite?: boolean,
optimisticUpdate?: boolean
) {
return JSON.stringify({
prefix: QUERY_KEY_PREFIX,
model,
operation,
args,
infinite: infinite === true,
optimisticUpdate: optimisticUpdate !== false,
});
}
function getMutationKey(model: string, operation: string) {
// use a random key since we don't have 1:1 mapping between mutation and query
// https://github.com/vercel/swr/discussions/2461#discussioncomment-5281784
return JSON.stringify({ prefix: MUTATION_KEY_PREFIX, model, operation, r: Date.now() });
}
function parseQueryKey(key: unknown): QueryKey | undefined {
let keyValue: any = key;
if (typeof key === 'string') {
try {
keyValue = JSON.parse(key);
} catch {
return undefined;
}
}
return keyValue?.prefix === QUERY_KEY_PREFIX ? (keyValue as QueryKey) : undefined;
}
/**
* Makes a model query with SWR.
*
* @param model Model name
* @param operation Prisma operation (e.g, `findMany`)
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
* @param options Query options
* @returns SWR response
*/
export function useModelQuery<Result, Error = unknown>(
model: string,
operation: string,
args?: unknown,
options?: QueryOptions<Result, Error>
): SWRResponse<Result, Error> {
const { endpoint, fetch } = useHooksContext();
const key = options?.disabled
? null
: getQueryKey(model, operation, args, false, options?.optimisticUpdate !== false);
const url = makeUrl(`${endpoint}/${lowerCaseFirst(model)}/${operation}`, args);
return useSWR<Result, Error>(key, () => fetcher<Result, false>(url, undefined, fetch, false), options);
}
/**
* Function for computing the query args for fetching a page during an infinite query.
*/
export type GetNextArgs<Args, Result> = (pageIndex: number, previousPageData: Result | null) => Args | null;
/**
* Makes an infinite GET request with SWR.
*
* @param model Model name
* @param operation Prisma operation (e.g, `findMany`)
* @param getNextArgs Function for computing the query args for a page
* @param options Query options
* @returns SWR infinite query response
*/
export function useInfiniteModelQuery<Args, Result, Error = unknown>(
model: string,
operation: string,
getNextArgs: GetNextArgs<Args, any>,
options?: InfiniteQueryOptions<Result, Error>
): SWRInfiniteResponse<Result, Error> {
const { endpoint, fetch } = useHooksContext();
const getKey = (pageIndex: number, previousPageData: Result | null) => {
if (options?.disabled) {
return null;
}
const nextArgs = getNextArgs(pageIndex, previousPageData);
return nextArgs !== null // null means reached the end
? getQueryKey(model, operation, nextArgs, true, false)
: null;
};
return useSWRInfinite<Result, Error>(
getKey,
(key: unknown) => {
const parsedKey = parseQueryKey(key);
if (parsedKey) {
const { model, operation, args } = parsedKey;
const url = makeUrl(`${endpoint}/${lowerCaseFirst(model)}/${operation}`, args);
return fetcher<Result, false>(url, undefined, fetch, false);
} else {
throw new Error('Invalid query key: ' + key);
}
},
options
);
}
export function useModelMutation<Args, Result, CheckReadBack extends boolean = boolean>(
model: string,
method: 'POST' | 'PUT' | 'DELETE',
operation: string,
modelMeta: ModelMeta,
options?: MutationOptions<CheckReadBack extends true ? Result | undefined : Result, unknown, Args>,
checkReadBack?: CheckReadBack
) {
const { endpoint, fetch, logging } = useHooksContext();
const invalidate = options?.revalidate !== false ? useInvalidation(model, modelMeta) : undefined;
const { cache, mutate } = useSWRConfig();
return useSWRMutation(
getMutationKey(model, operation),
(_key, { arg }: { arg: any }) => {
if (options?.optimisticUpdate) {
optimisticUpdate(model, operation, arg, options, modelMeta, cache, mutate, logging);
}
const url = `${endpoint}/${lowerCaseFirst(model)}/${operation}`;
return mutationRequest(method, url, arg, invalidate, fetch, checkReadBack);
},
options
);
}
/**
* Makes a mutation request.
*
* @param url The request URL
* @param data The request data
* @param invalidate Function for invalidating a query
*/
export async function mutationRequest<Result, C extends boolean = boolean>(
method: 'POST' | 'PUT' | 'DELETE',
url: string,
data: unknown,
invalidate?: Invalidator,
fetch?: FetchFn,
checkReadBack?: C
): Promise<C extends true ? Result | undefined : Result> {
const reqUrl = method === 'DELETE' ? makeUrl(url, data) : url;
const r = await fetcher<Result, C>(
reqUrl,
{
method,
headers: {
'content-type': 'application/json',
},
body: data ? marshal(data) : undefined,
},
fetch,
checkReadBack
);
if (invalidate) {
await invalidate(getOperationFromUrl(url), data);
}
return r;
}
// function for invalidating queries related to mutation represented by its operation and args
type Invalidator = (operation: string, args?: unknown) => ReturnType<ScopedMutator>;
export function useInvalidation(model: string, modelMeta: ModelMeta): Invalidator {
// https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys-from-regex
const { logging } = useHooksContext();
const { cache, mutate } = useSWRConfig();
return async (operation: string, args: unknown) => {
if (!(cache instanceof Map)) {
throw new Error('mutate requires the cache provider to be a Map instance');
}
const mutatedModels = await getMutatedModels(model, operation as PrismaWriteActionType, args, modelMeta);
const keys = Array.from(cache.keys()).filter((key: unknown) => {
const parsedKey = parseQueryKey(key);
if (!parsedKey) {
return false;
}
const modelsRead = getReadModels(parsedKey.model, modelMeta, parsedKey.args);
return modelsRead.some((m) => mutatedModels.includes(m));
});
if (logging) {
keys.forEach((key) => {
console.log(`Invalidating query ${key} due to mutation "${model}.${operation}"`);
});
}
const mutations = keys.map((key) => {
const parsedKey = parseQueryKey(key);
// FIX: special handling for infinite query keys, but still not working
// https://github.com/vercel/swr/discussions/2843
return mutate(parsedKey?.infinite ? unstable_serialize(() => key) : key);
});
return Promise.all(mutations);
};
}
/**
* Makes fetch request for queries and mutations.
*/
export async function fetcher<R, C extends boolean>(
url: string,
options?: RequestInit,
customFetch?: FetchFn,
checkReadBack?: C
): Promise<C extends true ? R | undefined : R> {
// Note: 'cross-fetch' is supposed to handle fetch compatibility
// but it doesn't work for cloudflare workers
const _fetch =
customFetch ??
// check if fetch is available globally
(typeof fetch === 'function'
? fetch
: // fallback to 'cross-fetch' if otherwise
(await import('cross-fetch')).default);
const res = await _fetch(url, options);
if (!res.ok) {
const errData = unmarshal(await res.text());
if (
checkReadBack !== false &&
errData.error?.prisma &&
errData.error?.code === 'P2004' &&
errData.error?.reason === 'RESULT_NOT_READABLE'
) {
// policy doesn't allow mutation result to be read back, just return undefined
return undefined as any;
}
const error: Error & { info?: unknown; status?: number } = new Error(
'An error occurred while fetching the data.'
);
error.info = errData.error;
error.status = res.status;
throw error;
}
const textResult = await res.text();
try {
return unmarshal(textResult).data as R;
} catch (err) {
console.error(`Unable to deserialize data:`, textResult);
throw err;
}
}
function marshal(value: unknown) {
const { data, meta } = serialize(value);
if (meta) {
return JSON.stringify({ ...(data as any), meta: { serialization: meta } });
} else {
return JSON.stringify(data);
}
}
function unmarshal(value: string) {
const parsed = JSON.parse(value);
if (typeof parsed === 'object' && parsed?.data && parsed?.meta?.serialization) {
const deserializedData = deserialize(parsed.data, parsed.meta.serialization);
return { ...parsed, data: deserializedData };
} else {
return parsed;
}
}
function makeUrl(url: string, args: unknown) {
if (!args) {
return url;
}
const { data, meta } = serialize(args);
let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;
if (meta) {
result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;
}
return result;
}
function getOperationFromUrl(url: string) {
const parts = url.split('/');
const r = parts.pop();
if (!r) {
throw new Error(`Invalid URL: ${url}`);
} else {
return r;
}
}
async function optimisticUpdate(
mutationModel: string,
mutationOp: string,
mutationArgs: any,
options: MutationOptions<any, any, any> | undefined,
modelMeta: ModelMeta,
cache: Cache,
mutator: ScopedMutator,
logging = false
) {
const optimisticPromises: Array<Promise<void>> = [];
for (const key of cache.keys()) {
const parsedKey = parseQueryKey(key);
if (!parsedKey) {
continue;
}
if (!parsedKey.optimisticUpdate) {
if (logging) {
console.log(`Skipping optimistic update for ${key} due to opt-out`);
}
continue;
}
const cacheValue = cache.get(key);
if (cacheValue?.error) {
if (logging) {
console.warn(`Skipping optimistic update for ${key} due to error:`, cacheValue.error);
}
continue;
}
if (options?.optimisticDataProvider) {
const providerResult = await options.optimisticDataProvider({
queryModel: parsedKey.model,
queryOperation: parsedKey.operation,
queryArgs: parsedKey.args,
currentData: cacheValue?.data,
mutationArgs,
});
if (providerResult?.kind === 'Skip') {
if (logging) {
console.log(`Skipping optimistic update for ${key} due to custom provider`);
}
continue;
} else if (providerResult?.kind === 'Update') {
if (logging) {
console.log(`Optimistically updating query ${JSON.stringify(key)} due to provider`);
}
optimisticPromises.push(mutator(key, providerResult.data, { revalidate: false }));
continue;
}
}
if (!cacheValue) {
continue;
}
const mutatedData = await applyMutation(
parsedKey.model,
parsedKey.operation,
cacheValue.data,
mutationModel,
mutationOp as PrismaWriteActionType,
mutationArgs,
modelMeta,
logging
);
if (mutatedData !== undefined) {
// mutation applicable to this query, update cache
if (logging) {
console.log(
`Optimistically updating query ${JSON.stringify(
key
)} due to mutation "${mutationModel}.${mutationOp}"`
);
}
optimisticPromises.push(
mutator(key, mutatedData, {
// don't trigger revalidation here since we will do it
// when the remote mutation succeeds
revalidate: false,
})
);
}
}
return Promise.all(optimisticPromises);
}