@zenstackhq/swr 1.0.0-alpha.119

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 ZenStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # ZenStack React plugin & runtime
2
+
3
+ This package contains ZenStack plugin and runtime for ReactJS.
4
+
5
+ Visit [Homepage](https://zenstack.dev) for more details.
package/generator.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { DMMF } from '@prisma/generator-helper';
2
+ import { PluginOptions } from '@zenstackhq/sdk';
3
+ import { Model } from '@zenstackhq/sdk/ast';
4
+ export declare function generate(model: Model, options: PluginOptions, dmmf: DMMF.Document): Promise<string[]>;
package/generator.js ADDED
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.generate = void 0;
16
+ const sdk_1 = require("@zenstackhq/sdk");
17
+ const change_case_1 = require("change-case");
18
+ const fs_1 = __importDefault(require("fs"));
19
+ const lower_case_first_1 = require("lower-case-first");
20
+ const path_1 = __importDefault(require("path"));
21
+ const upper_case_first_1 = require("upper-case-first");
22
+ function generate(model, options, dmmf) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ let outDir = (0, sdk_1.requireOption)(options, 'output');
25
+ outDir = (0, sdk_1.resolvePath)(outDir, options);
26
+ const project = (0, sdk_1.createProject)();
27
+ const warnings = [];
28
+ const models = (0, sdk_1.getDataModels)(model);
29
+ generateIndex(project, outDir, models);
30
+ generateHelper(project, outDir, options.useSuperJson === true);
31
+ models.forEach((dataModel) => {
32
+ const mapping = dmmf.mappings.modelOperations.find((op) => op.model === dataModel.name);
33
+ if (!mapping) {
34
+ warnings.push(`Unable to find mapping for model ${dataModel.name}`);
35
+ return;
36
+ }
37
+ generateModelHooks(project, outDir, dataModel, mapping);
38
+ });
39
+ yield (0, sdk_1.saveProject)(project);
40
+ return warnings;
41
+ });
42
+ }
43
+ exports.generate = generate;
44
+ function wrapReadbackErrorCheck(code) {
45
+ return `try {
46
+ ${code}
47
+ } catch (err: any) {
48
+ if (err.info?.prisma && err.info?.code === 'P2004' && err.info?.reason === '${sdk_1.CrudFailureReason.RESULT_NOT_READABLE}') {
49
+ // unable to readback data
50
+ return undefined;
51
+ } else {
52
+ throw err;
53
+ }
54
+ }`;
55
+ }
56
+ function generateModelHooks(project, outDir, model, mapping) {
57
+ const fileName = (0, change_case_1.paramCase)(model.name);
58
+ const sf = project.createSourceFile(path_1.default.join(outDir, `${fileName}.ts`), undefined, { overwrite: true });
59
+ sf.addStatements('/* eslint-disable */');
60
+ sf.addImportDeclaration({
61
+ namedImports: ['Prisma', model.name],
62
+ isTypeOnly: true,
63
+ moduleSpecifier: '@prisma/client',
64
+ });
65
+ sf.addStatements([
66
+ `import { useContext } from 'react';`,
67
+ `import { RequestHandlerContext, type RequestOptions } from './_helper';`,
68
+ `import * as request from './_helper';`,
69
+ ]);
70
+ const prefixesToMutate = ['find', 'aggregate', 'count', 'groupBy'];
71
+ const useMutation = sf.addFunction({
72
+ name: `useMutate${model.name}`,
73
+ isExported: true,
74
+ statements: [
75
+ 'const { endpoint } = useContext(RequestHandlerContext);',
76
+ `const prefixesToMutate = [${prefixesToMutate
77
+ .map((prefix) => '`${endpoint}/' + (0, lower_case_first_1.lowerCaseFirst)(model.name) + '/' + prefix + '`')
78
+ .join(', ')}];`,
79
+ 'const mutate = request.getMutate(prefixesToMutate);',
80
+ ],
81
+ });
82
+ const mutationFuncs = [];
83
+ // create is somehow named "createOne" in the DMMF
84
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
85
+ if (mapping.create || mapping.createOne) {
86
+ const argsType = `Prisma.${model.name}CreateArgs`;
87
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
88
+ const returnType = `Prisma.CheckSelect<T, ${model.name}, Prisma.${model.name}GetPayload<T>>`;
89
+ mutationFuncs.push(generateMutation(useMutation, model, 'post', 'create', argsType, inputType, returnType));
90
+ }
91
+ // createMany
92
+ if (mapping.createMany) {
93
+ const argsType = `Prisma.${model.name}CreateManyArgs`;
94
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
95
+ const returnType = `Prisma.BatchPayload`;
96
+ mutationFuncs.push(generateMutation(useMutation, model, 'post', 'createMany', argsType, inputType, returnType));
97
+ }
98
+ // findMany
99
+ if (mapping.findMany) {
100
+ const argsType = `Prisma.${model.name}FindManyArgs`;
101
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
102
+ const returnType = `Array<Prisma.${model.name}GetPayload<T>>`;
103
+ generateQueryHook(sf, model, 'findMany', argsType, inputType, returnType);
104
+ }
105
+ // findUnique
106
+ if (mapping.findUnique) {
107
+ const argsType = `Prisma.${model.name}FindUniqueArgs`;
108
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
109
+ const returnType = `Prisma.${model.name}GetPayload<T>`;
110
+ generateQueryHook(sf, model, 'findUnique', argsType, inputType, returnType);
111
+ }
112
+ // findFirst
113
+ if (mapping.findFirst) {
114
+ const argsType = `Prisma.${model.name}FindFirstArgs`;
115
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
116
+ const returnType = `Prisma.${model.name}GetPayload<T>`;
117
+ generateQueryHook(sf, model, 'findFirst', argsType, inputType, returnType);
118
+ }
119
+ // update
120
+ // update is somehow named "updateOne" in the DMMF
121
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
122
+ if (mapping.update || mapping.updateOne) {
123
+ const argsType = `Prisma.${model.name}UpdateArgs`;
124
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
125
+ const returnType = `Prisma.${model.name}GetPayload<T>`;
126
+ mutationFuncs.push(generateMutation(useMutation, model, 'put', 'update', argsType, inputType, returnType));
127
+ }
128
+ // updateMany
129
+ if (mapping.updateMany) {
130
+ const argsType = `Prisma.${model.name}UpdateManyArgs`;
131
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
132
+ const returnType = `Prisma.BatchPayload`;
133
+ mutationFuncs.push(generateMutation(useMutation, model, 'put', 'updateMany', argsType, inputType, returnType));
134
+ }
135
+ // upsert
136
+ // upsert is somehow named "upsertOne" in the DMMF
137
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
138
+ if (mapping.upsert || mapping.upsertOne) {
139
+ const argsType = `Prisma.${model.name}UpsertArgs`;
140
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
141
+ const returnType = `Prisma.${model.name}GetPayload<T>`;
142
+ mutationFuncs.push(generateMutation(useMutation, model, 'post', 'upsert', argsType, inputType, returnType));
143
+ }
144
+ // del
145
+ // delete is somehow named "deleteOne" in the DMMF
146
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
147
+ if (mapping.delete || mapping.deleteOne) {
148
+ const argsType = `Prisma.${model.name}DeleteArgs`;
149
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
150
+ const returnType = `Prisma.${model.name}GetPayload<T>`;
151
+ mutationFuncs.push(generateMutation(useMutation, model, 'delete', 'delete', argsType, inputType, returnType));
152
+ }
153
+ // deleteMany
154
+ if (mapping.deleteMany) {
155
+ const argsType = `Prisma.${model.name}DeleteManyArgs`;
156
+ const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
157
+ const returnType = `Prisma.BatchPayload`;
158
+ mutationFuncs.push(generateMutation(useMutation, model, 'delete', 'deleteMany', argsType, inputType, returnType));
159
+ }
160
+ // aggregate
161
+ if (mapping.aggregate) {
162
+ const argsType = `Prisma.${model.name}AggregateArgs`;
163
+ const inputType = `Prisma.Subset<T, ${argsType}>`;
164
+ const returnType = `Prisma.Get${model.name}AggregateType<T>`;
165
+ generateQueryHook(sf, model, 'aggregate', argsType, inputType, returnType);
166
+ }
167
+ // groupBy
168
+ if (mapping.groupBy) {
169
+ const typeParameters = [
170
+ `T extends Prisma.${model.name}GroupByArgs`,
171
+ `HasSelectOrTake extends Prisma.Or<Prisma.Extends<'skip', Prisma.Keys<T>>, Prisma.Extends<'take', Prisma.Keys<T>>>`,
172
+ `OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.${model.name}GroupByArgs['orderBy'] }: { orderBy?: Prisma.${model.name}GroupByArgs['orderBy'] },`,
173
+ `OrderFields extends Prisma.ExcludeUnderscoreKeys<Prisma.Keys<Prisma.MaybeTupleToUnion<T['orderBy']>>>`,
174
+ `ByFields extends Prisma.TupleToUnion<T['by']>`,
175
+ `ByValid extends Prisma.Has<ByFields, OrderFields>`,
176
+ `HavingFields extends Prisma.GetHavingFields<T['having']>`,
177
+ `HavingValid extends Prisma.Has<ByFields, HavingFields>`,
178
+ `ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False`,
179
+ `InputErrors extends ByEmpty extends Prisma.True
180
+ ? \`Error: "by" must not be empty.\`
181
+ : HavingValid extends Prisma.False
182
+ ? {
183
+ [P in HavingFields]: P extends ByFields
184
+ ? never
185
+ : P extends string
186
+ ? \`Error: Field "\${P}" used in "having" needs to be provided in "by".\`
187
+ : [
188
+ Error,
189
+ 'Field ',
190
+ P,
191
+ \` in "having" needs to be provided in "by"\`,
192
+ ]
193
+ }[HavingFields]
194
+ : 'take' extends Prisma.Keys<T>
195
+ ? 'orderBy' extends Prisma.Keys<T>
196
+ ? ByValid extends Prisma.True
197
+ ? {}
198
+ : {
199
+ [P in OrderFields]: P extends ByFields
200
+ ? never
201
+ : \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
202
+ }[OrderFields]
203
+ : 'Error: If you provide "take", you also need to provide "orderBy"'
204
+ : 'skip' extends Prisma.Keys<T>
205
+ ? 'orderBy' extends Prisma.Keys<T>
206
+ ? ByValid extends Prisma.True
207
+ ? {}
208
+ : {
209
+ [P in OrderFields]: P extends ByFields
210
+ ? never
211
+ : \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
212
+ }[OrderFields]
213
+ : 'Error: If you provide "skip", you also need to provide "orderBy"'
214
+ : ByValid extends Prisma.True
215
+ ? {}
216
+ : {
217
+ [P in OrderFields]: P extends ByFields
218
+ ? never
219
+ : \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
220
+ }[OrderFields]`,
221
+ ];
222
+ const inputType = `Prisma.SubsetIntersection<T, Prisma.${model.name}GroupByArgs, OrderByArg> & InputErrors`;
223
+ const returnType = `{} extends InputErrors ?
224
+ Array<Prisma.PickArray<Prisma.${model.name}GroupByOutputType, T['by']> &
225
+ {
226
+ [P in ((keyof T) & (keyof Prisma.${model.name}GroupByOutputType))]: P extends '_count'
227
+ ? T[P] extends boolean
228
+ ? number
229
+ : Prisma.GetScalarType<T[P], Prisma.${model.name}GroupByOutputType[P]>
230
+ : Prisma.GetScalarType<T[P], Prisma.${model.name}GroupByOutputType[P]>
231
+ }
232
+ > : InputErrors`;
233
+ generateQueryHook(sf, model, 'groupBy', '', inputType, returnType, typeParameters);
234
+ }
235
+ // somehow dmmf doesn't contain "count" operation, so we unconditionally add it here
236
+ {
237
+ const argsType = `Prisma.${model.name}CountArgs`;
238
+ const inputType = `Prisma.Subset<T, ${argsType}>`;
239
+ const returnType = `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType<T['select'], Prisma.${model.name}CountAggregateOutputType> : number`;
240
+ generateQueryHook(sf, model, 'count', argsType, inputType, returnType);
241
+ }
242
+ useMutation.addStatements(`return { ${mutationFuncs.join(', ')} };`);
243
+ }
244
+ function generateIndex(project, outDir, models) {
245
+ const sf = project.createSourceFile(path_1.default.join(outDir, 'index.ts'), undefined, { overwrite: true });
246
+ sf.addStatements(models.map((d) => `export * from './${(0, change_case_1.paramCase)(d.name)}';`));
247
+ sf.addStatements(`export * from './_helper';`);
248
+ }
249
+ function generateQueryHook(sf, model, operation, argsType, inputType, returnType, typeParameters) {
250
+ const modelRouteName = (0, lower_case_first_1.lowerCaseFirst)(model.name);
251
+ sf.addFunction({
252
+ name: `use${(0, upper_case_first_1.upperCaseFirst)(operation)}${model.name}`,
253
+ typeParameters: typeParameters !== null && typeParameters !== void 0 ? typeParameters : [`T extends ${argsType}`],
254
+ isExported: true,
255
+ parameters: [
256
+ {
257
+ name: 'args?',
258
+ type: inputType,
259
+ },
260
+ {
261
+ name: 'options?',
262
+ type: `RequestOptions<${returnType}>`,
263
+ },
264
+ ],
265
+ })
266
+ .addBody()
267
+ .addStatements([
268
+ 'const { endpoint } = useContext(RequestHandlerContext);',
269
+ `return request.get<${returnType}>(\`\${endpoint}/${modelRouteName}/findMany\`, args, options);`,
270
+ ]);
271
+ }
272
+ function generateMutation(func, model, method, operation, argsType, inputType, returnType) {
273
+ const modelRouteName = (0, lower_case_first_1.lowerCaseFirst)(model.name);
274
+ const funcName = `${operation}${model.name}`;
275
+ const fetcherFunc = method === 'delete' ? 'del' : method;
276
+ func.addFunction({
277
+ name: funcName,
278
+ isAsync: true,
279
+ typeParameters: [`T extends ${argsType}`],
280
+ parameters: [
281
+ {
282
+ name: 'args',
283
+ type: inputType,
284
+ },
285
+ ],
286
+ })
287
+ .addBody()
288
+ .addStatements([
289
+ wrapReadbackErrorCheck(`return await request.${fetcherFunc}<${returnType}>(\`\${endpoint}/${modelRouteName}/${operation}\`, args, mutate);`),
290
+ ]);
291
+ return funcName;
292
+ }
293
+ function generateHelper(project, outDir, useSuperJson) {
294
+ const helperContent = fs_1.default.readFileSync(path_1.default.join(__dirname, './res/helper.ts'), 'utf-8');
295
+ const marshalContent = fs_1.default.readFileSync(path_1.default.join(__dirname, useSuperJson ? './res/marshal-superjson.ts' : './res/marshal-json.ts'), 'utf-8');
296
+ project.createSourceFile(path_1.default.join(outDir, '_helper.ts'), `${helperContent}\n${marshalContent}`, {
297
+ overwrite: true,
298
+ });
299
+ }
300
+ //# sourceMappingURL=generator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,yCAQyB;AAEzB,6CAAwC;AACxC,4CAAoB;AACpB,uDAAkD;AAClD,gDAAwB;AAExB,uDAAkD;AAElD,SAAsB,QAAQ,CAAC,KAAY,EAAE,OAAsB,EAAE,IAAmB;;QACpF,IAAI,MAAM,GAAG,IAAA,mBAAa,EAA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per';
2
+ import type { PluginOptions } from '@zenstackhq/sdk';
3
+ import type { Model } from '@zenstackhq/sdk/ast';
4
+ export declare const name = "SWR";
5
+ export default function run(model: Model, options: PluginOptions, dmmf: DMMF.Document): Promise<string[]>;
package/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.name = void 0;
13
+ const generator_1 = require("./generator");
14
+ exports.name = 'SWR';
15
+ function run(model, options, dmmf) {
16
+ return __awaiter(this, void 0, void 0, function* () {
17
+ return (0, generator_1.generate)(model, options, dmmf);
18
+ });
19
+ }
20
+ exports.default = run;
21
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,2CAAuC;AAE1B,QAAA,IAAI,GAAG,KAAK,CAAC;AAE1B,SAA8B,GAAG,CAAC,KAAY,EAAE,OAAsB,EAAE,IAAmB;;QACvF,OAAO,IAAA,oBAAQ,EAAC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC1C,CAAC;CAAA;AAFD,sBAEC"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@zenstackhq/swr",
3
+ "displayName": "ZenStack plugin for generating SWR hooks",
4
+ "version": "1.0.0-alpha.119",
5
+ "description": "ZenStack plugin for generating SWR hooks",
6
+ "main": "index.js",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/zenstackhq/zenstack"
10
+ },
11
+ "publishConfig": {
12
+ "directory": "dist",
13
+ "linkDirectory": true
14
+ },
15
+ "keywords": [],
16
+ "author": "ZenStack Team",
17
+ "license": "MIT",
18
+ "dependencies": {
19
+ "@prisma/generator-helper": "^4.7.1",
20
+ "change-case": "^4.1.2",
21
+ "decimal.js": "^10.4.2",
22
+ "lower-case-first": "^2.0.2",
23
+ "superjson": "^1.11.0",
24
+ "ts-morph": "^16.0.0",
25
+ "upper-case-first": "^2.0.2",
26
+ "@zenstackhq/sdk": "1.0.0-alpha.119"
27
+ },
28
+ "devDependencies": {
29
+ "@tanstack/react-query": "^4.28.0",
30
+ "@types/jest": "^29.5.0",
31
+ "@types/lower-case-first": "^1.0.1",
32
+ "@types/react": "^18.0.26",
33
+ "@types/tmp": "^0.2.3",
34
+ "@types/upper-case-first": "^1.1.2",
35
+ "copyfiles": "^2.4.1",
36
+ "jest": "^29.5.0",
37
+ "react": "^17.0.2 || ^18",
38
+ "react-dom": "^17.0.2 || ^18",
39
+ "rimraf": "^3.0.2",
40
+ "swr": "^2.0.3",
41
+ "ts-jest": "^29.0.5",
42
+ "typescript": "^4.9.4",
43
+ "@zenstackhq/testtools": "1.0.0-alpha.119"
44
+ },
45
+ "scripts": {
46
+ "clean": "rimraf dist",
47
+ "build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist",
48
+ "watch": "tsc --watch",
49
+ "lint": "eslint src --ext ts",
50
+ "test": "jest",
51
+ "publish-dev": "pnpm publish --tag dev"
52
+ }
53
+ }
package/res/helper.ts ADDED
@@ -0,0 +1,147 @@
1
+ import { createContext } from 'react';
2
+ import type { MutatorCallback, MutatorOptions, SWRResponse } from 'swr';
3
+ import useSWR, { useSWRConfig } from 'swr';
4
+
5
+ /**
6
+ * Context type for configuring react hooks.
7
+ */
8
+ export type RequestHandlerContext = {
9
+ endpoint: string;
10
+ };
11
+
12
+ /**
13
+ * Context for configuring react hooks.
14
+ */
15
+ export const RequestHandlerContext = createContext<RequestHandlerContext>({
16
+ endpoint: '/api/model',
17
+ });
18
+
19
+ /**
20
+ * Context provider.
21
+ */
22
+ export const Provider = RequestHandlerContext.Provider;
23
+
24
+ /**
25
+ * Client request options
26
+ */
27
+ export type RequestOptions<T> = {
28
+ // disable data fetching
29
+ disabled?: boolean;
30
+ initialData?: T;
31
+ };
32
+
33
+ /**
34
+ * Makes a GET request with SWR.
35
+ *
36
+ * @param url The request URL.
37
+ * @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
38
+ * @returns SWR response
39
+ */
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
+ export function get<Result, Error = any>(
42
+ url: string | null,
43
+ args?: unknown,
44
+ options?: RequestOptions<Result>
45
+ ): SWRResponse<Result, Error> {
46
+ const reqUrl = options?.disabled ? null : url ? makeUrl(url, args) : null;
47
+ return useSWR<Result, Error>(reqUrl, fetcher, {
48
+ fallbackData: options?.initialData,
49
+ });
50
+ }
51
+
52
+ /**
53
+ * Makes a POST request.
54
+ *
55
+ * @param url The request URL.
56
+ * @param data The request data.
57
+ * @param mutate Mutator for invalidating cache.
58
+ */
59
+ export async function post<Result>(url: string, data: unknown, mutate: Mutator): Promise<Result> {
60
+ const r: Result = await fetcher(url, {
61
+ method: 'POST',
62
+ headers: {
63
+ 'content-type': 'application/json',
64
+ },
65
+ body: marshal(data),
66
+ });
67
+ mutate();
68
+ return r;
69
+ }
70
+
71
+ /**
72
+ * Makes a PUT request.
73
+ *
74
+ * @param url The request URL.
75
+ * @param data The request data.
76
+ * @param mutate Mutator for invalidating cache.
77
+ */
78
+ export async function put<Result>(url: string, data: unknown, mutate: Mutator): Promise<Result> {
79
+ const r: Result = await fetcher(url, {
80
+ method: 'PUT',
81
+ headers: {
82
+ 'content-type': 'application/json',
83
+ },
84
+ body: marshal(data),
85
+ });
86
+ mutate();
87
+ return r;
88
+ }
89
+
90
+ /**
91
+ * Makes a DELETE request.
92
+ *
93
+ * @param url The request URL.
94
+ * @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
95
+ * @param mutate Mutator for invalidating cache.
96
+ */
97
+ export async function del<Result>(url: string, args: unknown, mutate: Mutator): Promise<Result> {
98
+ const reqUrl = makeUrl(url, args);
99
+ const r: Result = await fetcher(reqUrl, {
100
+ method: 'DELETE',
101
+ });
102
+ const path = url.split('/');
103
+ path.pop();
104
+ mutate();
105
+ return r;
106
+ }
107
+
108
+ type Mutator = (
109
+ data?: unknown | Promise<unknown> | MutatorCallback,
110
+ opts?: boolean | MutatorOptions
111
+ ) => Promise<unknown[]>;
112
+
113
+ export function getMutate(prefixes: string[]): Mutator {
114
+ // https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys-from-regex
115
+ const { cache, mutate } = useSWRConfig();
116
+ return (data?: unknown | Promise<unknown> | MutatorCallback, opts?: boolean | MutatorOptions) => {
117
+ if (!(cache instanceof Map)) {
118
+ throw new Error('mutate requires the cache provider to be a Map instance');
119
+ }
120
+
121
+ const keys = Array.from(cache.keys()).filter(
122
+ (k) => typeof k === 'string' && prefixes.some((prefix) => k.startsWith(prefix))
123
+ ) as string[];
124
+ const mutations = keys.map((key) => mutate(key, data, opts));
125
+ return Promise.all(mutations);
126
+ };
127
+ }
128
+
129
+ export async function fetcher<R>(url: string, options?: RequestInit) {
130
+ const res = await fetch(url, options);
131
+ if (!res.ok) {
132
+ const error: Error & { info?: unknown; status?: number } = new Error(
133
+ 'An error occurred while fetching the data.'
134
+ );
135
+ error.info = unmarshal(await res.text());
136
+ error.status = res.status;
137
+ throw error;
138
+ }
139
+
140
+ const textResult = await res.text();
141
+ try {
142
+ return unmarshal(textResult) as R;
143
+ } catch (err) {
144
+ console.error(`Unable to deserialize data:`, textResult);
145
+ throw err;
146
+ }
147
+ }
@@ -0,0 +1,12 @@
1
+ function marshal(value: unknown) {
2
+ return JSON.stringify(value);
3
+ }
4
+
5
+ function unmarshal(value: string) {
6
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
+ return JSON.parse(value) as any;
8
+ }
9
+
10
+ function makeUrl(url: string, args: unknown) {
11
+ return args ? url + `?q=${encodeURIComponent(JSON.stringify(args))}` : url;
12
+ }
@@ -0,0 +1,20 @@
1
+ import superjson from 'superjson';
2
+
3
+ function marshal(value: unknown) {
4
+ return superjson.stringify(value);
5
+ }
6
+
7
+ function unmarshal(value: string) {
8
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
+ const j = JSON.parse(value) as any;
10
+ if (j?.json) {
11
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
+ return superjson.parse<any>(value);
13
+ } else {
14
+ return j;
15
+ }
16
+ }
17
+
18
+ function makeUrl(url: string, args: unknown) {
19
+ return args ? url + `?q=${encodeURIComponent(superjson.stringify(args))}` : url;
20
+ }