@zenstackhq/swr 1.0.0-beta.2 → 1.0.0-beta.20
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/generator.d.ts +1 -1
- package/generator.js +40 -49
- package/generator.js.map +1 -1
- package/package.json +12 -12
- package/runtime/index.d.ts +70 -0
- package/runtime/index.js +206 -0
- package/runtime/index.js.map +1 -0
- package/runtime/prisma-types.d.ts +17 -0
- package/runtime/prisma-types.js +5 -0
- package/runtime/prisma-types.js.map +1 -0
- package/res/helper.ts +0 -149
- package/res/marshal-json.ts +0 -12
- package/res/marshal-superjson.ts +0 -20
package/generator.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DMMF } from '@prisma/generator-helper';
|
|
1
|
+
import type { DMMF } from '@prisma/generator-helper';
|
|
2
2
|
import { PluginOptions } from '@zenstackhq/sdk';
|
|
3
3
|
import { Model } from '@zenstackhq/sdk/ast';
|
|
4
4
|
export declare function generate(model: Model, options: PluginOptions, dmmf: DMMF.Document): Promise<string[]>;
|
package/generator.js
CHANGED
|
@@ -15,9 +15,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
15
15
|
exports.generate = void 0;
|
|
16
16
|
const sdk_1 = require("@zenstackhq/sdk");
|
|
17
17
|
const change_case_1 = require("change-case");
|
|
18
|
-
const fs_1 = __importDefault(require("fs"));
|
|
19
18
|
const lower_case_first_1 = require("lower-case-first");
|
|
20
19
|
const path_1 = __importDefault(require("path"));
|
|
20
|
+
const semver_1 = __importDefault(require("semver"));
|
|
21
21
|
const upper_case_first_1 = require("upper-case-first");
|
|
22
22
|
function generate(model, options, dmmf) {
|
|
23
23
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -25,9 +25,11 @@ function generate(model, options, dmmf) {
|
|
|
25
25
|
outDir = (0, sdk_1.resolvePath)(outDir, options);
|
|
26
26
|
const project = (0, sdk_1.createProject)();
|
|
27
27
|
const warnings = [];
|
|
28
|
+
if (options.useSuperJson !== undefined) {
|
|
29
|
+
warnings.push('The option "useSuperJson" is deprecated. The generated hooks always use superjson for serialization.');
|
|
30
|
+
}
|
|
28
31
|
const models = (0, sdk_1.getDataModels)(model);
|
|
29
32
|
generateIndex(project, outDir, models);
|
|
30
|
-
generateHelper(project, outDir, options.useSuperJson === true);
|
|
31
33
|
models.forEach((dataModel) => {
|
|
32
34
|
const mapping = dmmf.mappings.modelOperations.find((op) => op.model === dataModel.name);
|
|
33
35
|
if (!mapping) {
|
|
@@ -41,38 +43,29 @@ function generate(model, options, dmmf) {
|
|
|
41
43
|
});
|
|
42
44
|
}
|
|
43
45
|
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
46
|
function generateModelHooks(project, outDir, model, mapping) {
|
|
57
47
|
const fileName = (0, change_case_1.paramCase)(model.name);
|
|
58
48
|
const sf = project.createSourceFile(path_1.default.join(outDir, `${fileName}.ts`), undefined, { overwrite: true });
|
|
59
49
|
sf.addStatements('/* eslint-disable */');
|
|
50
|
+
const prismaImport = (0, sdk_1.getPrismaClientImportSpec)(model.$container, outDir);
|
|
60
51
|
sf.addImportDeclaration({
|
|
61
52
|
namedImports: ['Prisma', model.name],
|
|
62
53
|
isTypeOnly: true,
|
|
63
|
-
moduleSpecifier:
|
|
54
|
+
moduleSpecifier: prismaImport,
|
|
64
55
|
});
|
|
65
56
|
sf.addStatements([
|
|
66
57
|
`import { useContext } from 'react';`,
|
|
67
|
-
`import { RequestHandlerContext, type RequestOptions } from '
|
|
68
|
-
`import * as request from '
|
|
58
|
+
`import { RequestHandlerContext, type RequestOptions, type PickEnumerable, type CheckSelect } from '@zenstackhq/swr/runtime';`,
|
|
59
|
+
`import * as request from '@zenstackhq/swr/runtime';`,
|
|
69
60
|
]);
|
|
61
|
+
const modelNameCap = (0, upper_case_first_1.upperCaseFirst)(model.name);
|
|
62
|
+
const prismaVersion = (0, sdk_1.getPrismaVersion)();
|
|
70
63
|
const prefixesToMutate = ['find', 'aggregate', 'count', 'groupBy'];
|
|
71
64
|
const useMutation = sf.addFunction({
|
|
72
65
|
name: `useMutate${model.name}`,
|
|
73
66
|
isExported: true,
|
|
74
67
|
statements: [
|
|
75
|
-
'const { endpoint } = useContext(RequestHandlerContext);',
|
|
68
|
+
'const { endpoint, fetch } = useContext(RequestHandlerContext);',
|
|
76
69
|
`const prefixesToMutate = [${prefixesToMutate
|
|
77
70
|
.map((prefix) => '`${endpoint}/' + (0, lower_case_first_1.lowerCaseFirst)(model.name) + '/' + prefix + '`')
|
|
78
71
|
.join(', ')}];`,
|
|
@@ -85,15 +78,15 @@ function generateModelHooks(project, outDir, model, mapping) {
|
|
|
85
78
|
if (mapping.create || mapping.createOne) {
|
|
86
79
|
const argsType = `Prisma.${model.name}CreateArgs`;
|
|
87
80
|
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
88
|
-
const returnType = `
|
|
89
|
-
mutationFuncs.push(generateMutation(useMutation, model, 'post', 'create', argsType, inputType, returnType));
|
|
81
|
+
const returnType = `CheckSelect<T, ${model.name}, Prisma.${model.name}GetPayload<T>>`;
|
|
82
|
+
mutationFuncs.push(generateMutation(useMutation, model, 'post', 'create', argsType, inputType, returnType, true));
|
|
90
83
|
}
|
|
91
84
|
// createMany
|
|
92
85
|
if (mapping.createMany) {
|
|
93
86
|
const argsType = `Prisma.${model.name}CreateManyArgs`;
|
|
94
87
|
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
95
88
|
const returnType = `Prisma.BatchPayload`;
|
|
96
|
-
mutationFuncs.push(generateMutation(useMutation, model, 'post', 'createMany', argsType, inputType, returnType));
|
|
89
|
+
mutationFuncs.push(generateMutation(useMutation, model, 'post', 'createMany', argsType, inputType, returnType, false));
|
|
97
90
|
}
|
|
98
91
|
// findMany
|
|
99
92
|
if (mapping.findMany) {
|
|
@@ -123,14 +116,14 @@ function generateModelHooks(project, outDir, model, mapping) {
|
|
|
123
116
|
const argsType = `Prisma.${model.name}UpdateArgs`;
|
|
124
117
|
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
125
118
|
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
126
|
-
mutationFuncs.push(generateMutation(useMutation, model, 'put', 'update', argsType, inputType, returnType));
|
|
119
|
+
mutationFuncs.push(generateMutation(useMutation, model, 'put', 'update', argsType, inputType, returnType, true));
|
|
127
120
|
}
|
|
128
121
|
// updateMany
|
|
129
122
|
if (mapping.updateMany) {
|
|
130
123
|
const argsType = `Prisma.${model.name}UpdateManyArgs`;
|
|
131
124
|
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
132
125
|
const returnType = `Prisma.BatchPayload`;
|
|
133
|
-
mutationFuncs.push(generateMutation(useMutation, model, 'put', 'updateMany', argsType, inputType, returnType));
|
|
126
|
+
mutationFuncs.push(generateMutation(useMutation, model, 'put', 'updateMany', argsType, inputType, returnType, false));
|
|
134
127
|
}
|
|
135
128
|
// upsert
|
|
136
129
|
// upsert is somehow named "upsertOne" in the DMMF
|
|
@@ -139,7 +132,7 @@ function generateModelHooks(project, outDir, model, mapping) {
|
|
|
139
132
|
const argsType = `Prisma.${model.name}UpsertArgs`;
|
|
140
133
|
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
141
134
|
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
142
|
-
mutationFuncs.push(generateMutation(useMutation, model, 'post', 'upsert', argsType, inputType, returnType));
|
|
135
|
+
mutationFuncs.push(generateMutation(useMutation, model, 'post', 'upsert', argsType, inputType, returnType, true));
|
|
143
136
|
}
|
|
144
137
|
// del
|
|
145
138
|
// delete is somehow named "deleteOne" in the DMMF
|
|
@@ -148,30 +141,35 @@ function generateModelHooks(project, outDir, model, mapping) {
|
|
|
148
141
|
const argsType = `Prisma.${model.name}DeleteArgs`;
|
|
149
142
|
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
150
143
|
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
151
|
-
mutationFuncs.push(generateMutation(useMutation, model, 'delete', 'delete', argsType, inputType, returnType));
|
|
144
|
+
mutationFuncs.push(generateMutation(useMutation, model, 'delete', 'delete', argsType, inputType, returnType, true));
|
|
152
145
|
}
|
|
153
146
|
// deleteMany
|
|
154
147
|
if (mapping.deleteMany) {
|
|
155
148
|
const argsType = `Prisma.${model.name}DeleteManyArgs`;
|
|
156
149
|
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
157
150
|
const returnType = `Prisma.BatchPayload`;
|
|
158
|
-
mutationFuncs.push(generateMutation(useMutation, model, 'delete', 'deleteMany', argsType, inputType, returnType));
|
|
151
|
+
mutationFuncs.push(generateMutation(useMutation, model, 'delete', 'deleteMany', argsType, inputType, returnType, false));
|
|
159
152
|
}
|
|
160
153
|
// aggregate
|
|
161
154
|
if (mapping.aggregate) {
|
|
162
|
-
const argsType = `Prisma.${
|
|
155
|
+
const argsType = `Prisma.${modelNameCap}AggregateArgs`;
|
|
163
156
|
const inputType = `Prisma.Subset<T, ${argsType}>`;
|
|
164
|
-
const returnType = `Prisma.Get${
|
|
157
|
+
const returnType = `Prisma.Get${modelNameCap}AggregateType<T>`;
|
|
165
158
|
generateQueryHook(sf, model, 'aggregate', argsType, inputType, returnType);
|
|
166
159
|
}
|
|
167
160
|
// groupBy
|
|
168
161
|
if (mapping.groupBy) {
|
|
162
|
+
let useName = modelNameCap;
|
|
163
|
+
if (prismaVersion && semver_1.default.gte(prismaVersion, '5.0.0')) {
|
|
164
|
+
// prisma 4 and 5 different typing for "groupBy" and we have to deal with it separately
|
|
165
|
+
useName = model.name;
|
|
166
|
+
}
|
|
169
167
|
const typeParameters = [
|
|
170
|
-
`T extends Prisma.${
|
|
168
|
+
`T extends Prisma.${useName}GroupByArgs`,
|
|
171
169
|
`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.${
|
|
170
|
+
`OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.${useName}GroupByArgs['orderBy'] }: { orderBy?: Prisma.${useName}GroupByArgs['orderBy'] },`,
|
|
173
171
|
`OrderFields extends Prisma.ExcludeUnderscoreKeys<Prisma.Keys<Prisma.MaybeTupleToUnion<T['orderBy']>>>`,
|
|
174
|
-
`ByFields extends Prisma.
|
|
172
|
+
`ByFields extends Prisma.MaybeTupleToUnion<T['by']>`,
|
|
175
173
|
`ByValid extends Prisma.Has<ByFields, OrderFields>`,
|
|
176
174
|
`HavingFields extends Prisma.GetHavingFields<T['having']>`,
|
|
177
175
|
`HavingValid extends Prisma.Has<ByFields, HavingFields>`,
|
|
@@ -219,15 +217,15 @@ function generateModelHooks(project, outDir, model, mapping) {
|
|
|
219
217
|
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
220
218
|
}[OrderFields]`,
|
|
221
219
|
];
|
|
222
|
-
const inputType = `Prisma.SubsetIntersection<T, Prisma.${
|
|
220
|
+
const inputType = `Prisma.SubsetIntersection<T, Prisma.${useName}GroupByArgs, OrderByArg> & InputErrors`;
|
|
223
221
|
const returnType = `{} extends InputErrors ?
|
|
224
|
-
Array<
|
|
222
|
+
Array<PickEnumerable<Prisma.${modelNameCap}GroupByOutputType, T['by']> &
|
|
225
223
|
{
|
|
226
|
-
[P in ((keyof T) & (keyof Prisma.${
|
|
224
|
+
[P in ((keyof T) & (keyof Prisma.${modelNameCap}GroupByOutputType))]: P extends '_count'
|
|
227
225
|
? T[P] extends boolean
|
|
228
226
|
? number
|
|
229
|
-
: Prisma.GetScalarType<T[P], Prisma.${
|
|
230
|
-
: Prisma.GetScalarType<T[P], Prisma.${
|
|
227
|
+
: Prisma.GetScalarType<T[P], Prisma.${modelNameCap}GroupByOutputType[P]>
|
|
228
|
+
: Prisma.GetScalarType<T[P], Prisma.${modelNameCap}GroupByOutputType[P]>
|
|
231
229
|
}
|
|
232
230
|
> : InputErrors`;
|
|
233
231
|
generateQueryHook(sf, model, 'groupBy', '', inputType, returnType, typeParameters);
|
|
@@ -236,7 +234,7 @@ function generateModelHooks(project, outDir, model, mapping) {
|
|
|
236
234
|
{
|
|
237
235
|
const argsType = `Prisma.${model.name}CountArgs`;
|
|
238
236
|
const inputType = `Prisma.Subset<T, ${argsType}>`;
|
|
239
|
-
const returnType = `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType<T['select'], Prisma.${
|
|
237
|
+
const returnType = `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType<T['select'], Prisma.${modelNameCap}CountAggregateOutputType> : number`;
|
|
240
238
|
generateQueryHook(sf, model, 'count', argsType, inputType, returnType);
|
|
241
239
|
}
|
|
242
240
|
useMutation.addStatements(`return { ${mutationFuncs.join(', ')} };`);
|
|
@@ -244,7 +242,7 @@ function generateModelHooks(project, outDir, model, mapping) {
|
|
|
244
242
|
function generateIndex(project, outDir, models) {
|
|
245
243
|
const sf = project.createSourceFile(path_1.default.join(outDir, 'index.ts'), undefined, { overwrite: true });
|
|
246
244
|
sf.addStatements(models.map((d) => `export * from './${(0, change_case_1.paramCase)(d.name)}';`));
|
|
247
|
-
sf.addStatements(`export
|
|
245
|
+
sf.addStatements(`export { Provider } from '@zenstackhq/swr/runtime';`);
|
|
248
246
|
}
|
|
249
247
|
function generateQueryHook(sf, model, operation, argsType, inputType, returnType, typeParameters) {
|
|
250
248
|
const modelRouteName = (0, lower_case_first_1.lowerCaseFirst)(model.name);
|
|
@@ -265,11 +263,11 @@ function generateQueryHook(sf, model, operation, argsType, inputType, returnType
|
|
|
265
263
|
})
|
|
266
264
|
.addBody()
|
|
267
265
|
.addStatements([
|
|
268
|
-
'const { endpoint } = useContext(RequestHandlerContext);',
|
|
269
|
-
`return request.get<${returnType}>(\`\${endpoint}/${modelRouteName}/${operation}\`, args, options);`,
|
|
266
|
+
'const { endpoint, fetch } = useContext(RequestHandlerContext);',
|
|
267
|
+
`return request.get<${returnType}>(\`\${endpoint}/${modelRouteName}/${operation}\`, args, options, fetch);`,
|
|
270
268
|
]);
|
|
271
269
|
}
|
|
272
|
-
function generateMutation(func, model, method, operation, argsType, inputType, returnType) {
|
|
270
|
+
function generateMutation(func, model, method, operation, argsType, inputType, returnType, checkReadBack) {
|
|
273
271
|
const modelRouteName = (0, lower_case_first_1.lowerCaseFirst)(model.name);
|
|
274
272
|
const funcName = `${operation}${model.name}`;
|
|
275
273
|
const fetcherFunc = method === 'delete' ? 'del' : method;
|
|
@@ -286,15 +284,8 @@ function generateMutation(func, model, method, operation, argsType, inputType, r
|
|
|
286
284
|
})
|
|
287
285
|
.addBody()
|
|
288
286
|
.addStatements([
|
|
289
|
-
|
|
287
|
+
`return await request.${fetcherFunc}<${returnType}, ${checkReadBack}>(\`\${endpoint}/${modelRouteName}/${operation}\`, args, mutate, fetch, ${checkReadBack});`,
|
|
290
288
|
]);
|
|
291
289
|
return funcName;
|
|
292
290
|
}
|
|
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
291
|
//# sourceMappingURL=generator.js.map
|
package/generator.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,
|
|
1
|
+
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,yCASyB;AAEzB,6CAAwC;AACxC,uDAAkD;AAClD,gDAAwB;AACxB,oDAA4B;AAE5B,uDAAkD;AAElD,SAAsB,QAAQ,CAAC,KAAY,EAAE,OAAsB,EAAE,IAAmB;;QACpF,IAAI,MAAM,GAAG,IAAA,mBAAa,EAAS,OAAO,EAAE,QAAQ,CAAC,CAAC;QACtD,MAAM,GAAG,IAAA,iBAAW,EAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAEtC,MAAM,OAAO,GAAG,IAAA,mBAAa,GAAE,CAAC;QAChC,MAAM,QAAQ,GAAa,EAAE,CAAC;QAE9B,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,EAAE;YACpC,QAAQ,CAAC,IAAI,CACT,sGAAsG,CACzG,CAAC;SACL;QAED,MAAM,MAAM,GAAG,IAAA,mBAAa,EAAC,KAAK,CAAC,CAAC;QAEpC,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAEvC,MAAM,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;YACzB,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,IAAI,CAAC,CAAC;YACxF,IAAI,CAAC,OAAO,EAAE;gBACV,QAAQ,CAAC,IAAI,CAAC,oCAAoC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;gBACpE,OAAO;aACV;YACD,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE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AAc,IAAI,SAAS,4BAA4B,aAAa,IAAI;KAClK,CAAC,CAAC;IACP,OAAO,QAAQ,CAAC;AACpB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zenstackhq/swr",
|
|
3
3
|
"displayName": "ZenStack plugin for generating SWR hooks",
|
|
4
|
-
"version": "1.0.0-beta.
|
|
4
|
+
"version": "1.0.0-beta.20",
|
|
5
5
|
"description": "ZenStack plugin for generating SWR hooks",
|
|
6
6
|
"main": "index.js",
|
|
7
7
|
"repository": {
|
|
@@ -16,38 +16,38 @@
|
|
|
16
16
|
"author": "ZenStack Team",
|
|
17
17
|
"license": "MIT",
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@prisma/generator-helper": "^
|
|
19
|
+
"@prisma/generator-helper": "^5.0.0",
|
|
20
20
|
"change-case": "^4.1.2",
|
|
21
21
|
"decimal.js": "^10.4.2",
|
|
22
22
|
"lower-case-first": "^2.0.2",
|
|
23
|
-
"
|
|
23
|
+
"semver": "^7.3.8",
|
|
24
24
|
"ts-morph": "^16.0.0",
|
|
25
25
|
"upper-case-first": "^2.0.2",
|
|
26
|
-
"@zenstackhq/sdk": "1.0.0-beta.
|
|
26
|
+
"@zenstackhq/sdk": "1.0.0-beta.20",
|
|
27
|
+
"@zenstackhq/runtime": "1.0.0-beta.20"
|
|
27
28
|
},
|
|
28
29
|
"devDependencies": {
|
|
29
30
|
"@tanstack/react-query": "^4.28.0",
|
|
30
31
|
"@types/jest": "^29.5.0",
|
|
31
|
-
"@types/
|
|
32
|
-
"@types/react": "
|
|
32
|
+
"@types/node": "^18.0.0",
|
|
33
|
+
"@types/react": "18.2.0",
|
|
34
|
+
"@types/semver": "^7.3.13",
|
|
33
35
|
"@types/tmp": "^0.2.3",
|
|
34
|
-
"@types/upper-case-first": "^1.1.2",
|
|
35
36
|
"copyfiles": "^2.4.1",
|
|
36
37
|
"jest": "^29.5.0",
|
|
37
|
-
"react": "
|
|
38
|
-
"react-dom": "^17.0.2 || ^18",
|
|
38
|
+
"react": "18.2.0",
|
|
39
39
|
"rimraf": "^3.0.2",
|
|
40
40
|
"swr": "^2.0.3",
|
|
41
41
|
"ts-jest": "^29.0.5",
|
|
42
42
|
"typescript": "^4.9.4",
|
|
43
|
-
"@zenstackhq/testtools": "1.0.0-beta.
|
|
43
|
+
"@zenstackhq/testtools": "1.0.0-beta.20"
|
|
44
44
|
},
|
|
45
45
|
"scripts": {
|
|
46
46
|
"clean": "rimraf dist",
|
|
47
|
-
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE '
|
|
47
|
+
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE dist && pnpm pack dist --pack-destination '../../../../.build'",
|
|
48
48
|
"watch": "tsc --watch",
|
|
49
49
|
"lint": "eslint src --ext ts",
|
|
50
|
-
"test": "jest",
|
|
50
|
+
"test": "ZENSTACK_TEST=1 jest",
|
|
51
51
|
"publish-dev": "pnpm publish --tag dev"
|
|
52
52
|
}
|
|
53
53
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import type { MutatorCallback, MutatorOptions, SWRResponse } from 'swr';
|
|
3
|
+
export * from './prisma-types';
|
|
4
|
+
/**
|
|
5
|
+
* Function signature for `fetch`.
|
|
6
|
+
*/
|
|
7
|
+
export type FetchFn = (url: string, options?: RequestInit) => Promise<Response>;
|
|
8
|
+
/**
|
|
9
|
+
* Context type for configuring react hooks.
|
|
10
|
+
*/
|
|
11
|
+
export type RequestHandlerContext = {
|
|
12
|
+
/**
|
|
13
|
+
* The endpoint to use for the queries.
|
|
14
|
+
*/
|
|
15
|
+
endpoint: string;
|
|
16
|
+
/**
|
|
17
|
+
* A custom fetch function for sending the HTTP requests.
|
|
18
|
+
*/
|
|
19
|
+
fetch?: FetchFn;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Context for configuring react hooks.
|
|
23
|
+
*/
|
|
24
|
+
export declare const RequestHandlerContext: import("react").Context<RequestHandlerContext>;
|
|
25
|
+
/**
|
|
26
|
+
* Context provider.
|
|
27
|
+
*/
|
|
28
|
+
export declare const Provider: import("react").Provider<RequestHandlerContext>;
|
|
29
|
+
/**
|
|
30
|
+
* Client request options
|
|
31
|
+
*/
|
|
32
|
+
export type RequestOptions<T> = {
|
|
33
|
+
disabled?: boolean;
|
|
34
|
+
initialData?: T;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Makes a GET request with SWR.
|
|
38
|
+
*
|
|
39
|
+
* @param url The request URL.
|
|
40
|
+
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
|
|
41
|
+
* @returns SWR response
|
|
42
|
+
*/
|
|
43
|
+
export declare function get<Result, Error = any>(url: string | null, args?: unknown, options?: RequestOptions<Result>, fetch?: FetchFn): SWRResponse<Result, Error>;
|
|
44
|
+
/**
|
|
45
|
+
* Makes a POST request.
|
|
46
|
+
*
|
|
47
|
+
* @param url The request URL.
|
|
48
|
+
* @param data The request data.
|
|
49
|
+
* @param mutate Mutator for invalidating cache.
|
|
50
|
+
*/
|
|
51
|
+
export declare function post<Result, C extends boolean = boolean>(url: string, data: unknown, mutate: Mutator, fetch?: FetchFn, checkReadBack?: C): Promise<C extends true ? Result | undefined : Result>;
|
|
52
|
+
/**
|
|
53
|
+
* Makes a PUT request.
|
|
54
|
+
*
|
|
55
|
+
* @param url The request URL.
|
|
56
|
+
* @param data The request data.
|
|
57
|
+
* @param mutate Mutator for invalidating cache.
|
|
58
|
+
*/
|
|
59
|
+
export declare function put<Result, C extends boolean = boolean>(url: string, data: unknown, mutate: Mutator, fetch?: FetchFn, checkReadBack?: C): Promise<C extends true ? Result | undefined : Result>;
|
|
60
|
+
/**
|
|
61
|
+
* Makes a DELETE request.
|
|
62
|
+
*
|
|
63
|
+
* @param url The request URL.
|
|
64
|
+
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
|
|
65
|
+
* @param mutate Mutator for invalidating cache.
|
|
66
|
+
*/
|
|
67
|
+
export declare function del<Result, C extends boolean = boolean>(url: string, args: unknown, mutate: Mutator, fetch?: FetchFn, checkReadBack?: C): Promise<C extends true ? Result | undefined : Result>;
|
|
68
|
+
type Mutator = (data?: unknown | Promise<unknown> | MutatorCallback, opts?: boolean | MutatorOptions) => Promise<unknown[]>;
|
|
69
|
+
export declare function getMutate(prefixes: string[]): Mutator;
|
|
70
|
+
export declare function fetcher<R, C extends boolean>(url: string, options?: RequestInit, fetch?: FetchFn, checkReadBack?: C): Promise<C extends true ? R | undefined : R>;
|
package/runtime/index.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
26
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
27
|
+
};
|
|
28
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
29
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
30
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
31
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
32
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
33
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
34
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
38
|
+
exports.fetcher = exports.getMutate = exports.del = exports.put = exports.post = exports.get = exports.Provider = exports.RequestHandlerContext = void 0;
|
|
39
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
40
|
+
const browser_1 = require("@zenstackhq/runtime/browser");
|
|
41
|
+
const react_1 = require("react");
|
|
42
|
+
const swr_1 = __importStar(require("swr"));
|
|
43
|
+
__exportStar(require("./prisma-types"), exports);
|
|
44
|
+
/**
|
|
45
|
+
* Context for configuring react hooks.
|
|
46
|
+
*/
|
|
47
|
+
exports.RequestHandlerContext = (0, react_1.createContext)({
|
|
48
|
+
endpoint: '/api/model',
|
|
49
|
+
fetch: undefined,
|
|
50
|
+
});
|
|
51
|
+
/**
|
|
52
|
+
* Context provider.
|
|
53
|
+
*/
|
|
54
|
+
exports.Provider = exports.RequestHandlerContext.Provider;
|
|
55
|
+
/**
|
|
56
|
+
* Makes a GET request with SWR.
|
|
57
|
+
*
|
|
58
|
+
* @param url The request URL.
|
|
59
|
+
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
|
|
60
|
+
* @returns SWR response
|
|
61
|
+
*/
|
|
62
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
63
|
+
function get(url, args, options, fetch) {
|
|
64
|
+
const reqUrl = (options === null || options === void 0 ? void 0 : options.disabled) ? null : url ? makeUrl(url, args) : null;
|
|
65
|
+
return (0, swr_1.default)(reqUrl, (url) => fetcher(url, undefined, fetch, false), {
|
|
66
|
+
fallbackData: options === null || options === void 0 ? void 0 : options.initialData,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
exports.get = get;
|
|
70
|
+
/**
|
|
71
|
+
* Makes a POST request.
|
|
72
|
+
*
|
|
73
|
+
* @param url The request URL.
|
|
74
|
+
* @param data The request data.
|
|
75
|
+
* @param mutate Mutator for invalidating cache.
|
|
76
|
+
*/
|
|
77
|
+
function post(url, data, mutate, fetch, checkReadBack) {
|
|
78
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
79
|
+
const r = yield fetcher(url, {
|
|
80
|
+
method: 'POST',
|
|
81
|
+
headers: {
|
|
82
|
+
'content-type': 'application/json',
|
|
83
|
+
},
|
|
84
|
+
body: marshal(data),
|
|
85
|
+
}, fetch, checkReadBack);
|
|
86
|
+
mutate();
|
|
87
|
+
return r;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
exports.post = post;
|
|
91
|
+
/**
|
|
92
|
+
* Makes a PUT request.
|
|
93
|
+
*
|
|
94
|
+
* @param url The request URL.
|
|
95
|
+
* @param data The request data.
|
|
96
|
+
* @param mutate Mutator for invalidating cache.
|
|
97
|
+
*/
|
|
98
|
+
function put(url, data, mutate, fetch, checkReadBack) {
|
|
99
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
100
|
+
const r = yield fetcher(url, {
|
|
101
|
+
method: 'PUT',
|
|
102
|
+
headers: {
|
|
103
|
+
'content-type': 'application/json',
|
|
104
|
+
},
|
|
105
|
+
body: marshal(data),
|
|
106
|
+
}, fetch, checkReadBack);
|
|
107
|
+
mutate();
|
|
108
|
+
return r;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
exports.put = put;
|
|
112
|
+
/**
|
|
113
|
+
* Makes a DELETE request.
|
|
114
|
+
*
|
|
115
|
+
* @param url The request URL.
|
|
116
|
+
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
|
|
117
|
+
* @param mutate Mutator for invalidating cache.
|
|
118
|
+
*/
|
|
119
|
+
function del(url, args, mutate, fetch, checkReadBack) {
|
|
120
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
121
|
+
const reqUrl = makeUrl(url, args);
|
|
122
|
+
const r = yield fetcher(reqUrl, {
|
|
123
|
+
method: 'DELETE',
|
|
124
|
+
}, fetch, checkReadBack);
|
|
125
|
+
const path = url.split('/');
|
|
126
|
+
path.pop();
|
|
127
|
+
mutate();
|
|
128
|
+
return r;
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
exports.del = del;
|
|
132
|
+
function getMutate(prefixes) {
|
|
133
|
+
// https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys-from-regex
|
|
134
|
+
const { cache, mutate } = (0, swr_1.useSWRConfig)();
|
|
135
|
+
return (data, opts) => {
|
|
136
|
+
if (!(cache instanceof Map)) {
|
|
137
|
+
throw new Error('mutate requires the cache provider to be a Map instance');
|
|
138
|
+
}
|
|
139
|
+
const keys = Array.from(cache.keys()).filter((k) => typeof k === 'string' && prefixes.some((prefix) => k.startsWith(prefix)));
|
|
140
|
+
const mutations = keys.map((key) => mutate(key, data, opts));
|
|
141
|
+
return Promise.all(mutations);
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
exports.getMutate = getMutate;
|
|
145
|
+
function fetcher(url, options, fetch, checkReadBack) {
|
|
146
|
+
var _a, _b, _c;
|
|
147
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
148
|
+
const _fetch = fetch !== null && fetch !== void 0 ? fetch : window.fetch;
|
|
149
|
+
const res = yield _fetch(url, options);
|
|
150
|
+
if (!res.ok) {
|
|
151
|
+
const errData = unmarshal(yield res.text());
|
|
152
|
+
if (checkReadBack !== false &&
|
|
153
|
+
((_a = errData.error) === null || _a === void 0 ? void 0 : _a.prisma) &&
|
|
154
|
+
((_b = errData.error) === null || _b === void 0 ? void 0 : _b.code) === 'P2004' &&
|
|
155
|
+
((_c = errData.error) === null || _c === void 0 ? void 0 : _c.reason) === 'RESULT_NOT_READABLE') {
|
|
156
|
+
// policy doesn't allow mutation result to be read back, just return undefined
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
const error = new Error('An error occurred while fetching the data.');
|
|
160
|
+
error.info = errData.error;
|
|
161
|
+
error.status = res.status;
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
const textResult = yield res.text();
|
|
165
|
+
try {
|
|
166
|
+
return unmarshal(textResult).data;
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
console.error(`Unable to deserialize data:`, textResult);
|
|
170
|
+
throw err;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
exports.fetcher = fetcher;
|
|
175
|
+
function marshal(value) {
|
|
176
|
+
const { data, meta } = (0, browser_1.serialize)(value);
|
|
177
|
+
if (meta) {
|
|
178
|
+
return JSON.stringify(Object.assign(Object.assign({}, data), { meta: { serialization: meta } }));
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
return JSON.stringify(data);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function unmarshal(value) {
|
|
185
|
+
var _a;
|
|
186
|
+
const parsed = JSON.parse(value);
|
|
187
|
+
if (parsed.data && ((_a = parsed.meta) === null || _a === void 0 ? void 0 : _a.serialization)) {
|
|
188
|
+
const deserializedData = (0, browser_1.deserialize)(parsed.data, parsed.meta.serialization);
|
|
189
|
+
return Object.assign(Object.assign({}, parsed), { data: deserializedData });
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
return parsed;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
function makeUrl(url, args) {
|
|
196
|
+
if (!args) {
|
|
197
|
+
return url;
|
|
198
|
+
}
|
|
199
|
+
const { data, meta } = (0, browser_1.serialize)(args);
|
|
200
|
+
let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;
|
|
201
|
+
if (meta) {
|
|
202
|
+
result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;
|
|
203
|
+
}
|
|
204
|
+
return result;
|
|
205
|
+
}
|
|
206
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uDAAuD;AACvD,yDAAqE;AACrE,iCAAsC;AAEtC,2CAA2C;AAC3C,iDAA+B;AAsB/B;;GAEG;AACU,QAAA,qBAAqB,GAAG,IAAA,qBAAa,EAAwB;IACtE,QAAQ,EAAE,YAAY;IACtB,KAAK,EAAE,SAAS;CACnB,CAAC,CAAC;AAEH;;GAEG;AACU,QAAA,QAAQ,GAAG,6BAAqB,CAAC,QAAQ,CAAC;AAWvD;;;;;;GAMG;AACH,8DAA8D;AAC9D,SAAgB,GAAG,CACf,GAAkB,EAClB,IAAc,EACd,OAAgC,EAChC,KAAe;IAEf,MAAM,MAAM,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,EAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC1E,OAAO,IAAA,aAAM,EAAgB,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAgB,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,K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A,EAAE;QAC3C,MAAM,gBAAgB,GAAG,IAAA,qBAAW,EAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAC7E,uCAAY,MAAM,KAAE,IAAI,EAAE,gBAAgB,IAAG;KAChD;SAAM;QACH,OAAO,MAAM,CAAC;KACjB;AACL,CAAC;AAED,SAAS,OAAO,CAAC,GAAW,EAAE,IAAa;IACvC,IAAI,CAAC,IAAI,EAAE;QACP,OAAO,GAAG,CAAC;KACd;IAED,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,IAAA,mBAAS,EAAC,IAAI,CAAC,CAAC;IACvC,IAAI,MAAM,GAAG,GAAG,GAAG,MAAM,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;IACpE,IAAI,IAAI,EAAE;QACN,MAAM,IAAI,SAAS,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;KACpF;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type Enumerable<T> = T | Array<T>;
|
|
2
|
+
type _TupleToUnion<T> = T extends (infer E)[] ? E : never;
|
|
3
|
+
export type TupleToUnion<K extends readonly any[]> = _TupleToUnion<K>;
|
|
4
|
+
export type MaybeTupleToUnion<T> = T extends any[] ? TupleToUnion<T> : T;
|
|
5
|
+
export type PickEnumerable<T, K extends Enumerable<keyof T> | keyof T> = Pick<T, MaybeTupleToUnion<K>>;
|
|
6
|
+
type SelectAndInclude = {
|
|
7
|
+
select: any;
|
|
8
|
+
include: any;
|
|
9
|
+
};
|
|
10
|
+
type HasSelect = {
|
|
11
|
+
select: any;
|
|
12
|
+
};
|
|
13
|
+
type HasInclude = {
|
|
14
|
+
include: any;
|
|
15
|
+
};
|
|
16
|
+
export type CheckSelect<T, S, U> = T extends SelectAndInclude ? 'Please either choose `select` or `include`' : T extends HasSelect ? U : T extends HasInclude ? U : S;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
3
|
+
/// Types copied over from Prisma's generated code to avoid being broken due to Prisma upgrades
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
//# sourceMappingURL=prisma-types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prisma-types.js","sourceRoot":"","sources":["../../src/runtime/prisma-types.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,+FAA+F"}
|
package/res/helper.ts
DELETED
|
@@ -1,149 +0,0 @@
|
|
|
1
|
-
/* eslint-disable */
|
|
2
|
-
|
|
3
|
-
import { createContext } from 'react';
|
|
4
|
-
import type { MutatorCallback, MutatorOptions, SWRResponse } from 'swr';
|
|
5
|
-
import useSWR, { useSWRConfig } from 'swr';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Context type for configuring react hooks.
|
|
9
|
-
*/
|
|
10
|
-
export type RequestHandlerContext = {
|
|
11
|
-
endpoint: string;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Context for configuring react hooks.
|
|
16
|
-
*/
|
|
17
|
-
export const RequestHandlerContext = createContext<RequestHandlerContext>({
|
|
18
|
-
endpoint: '/api/model',
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Context provider.
|
|
23
|
-
*/
|
|
24
|
-
export const Provider = RequestHandlerContext.Provider;
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Client request options
|
|
28
|
-
*/
|
|
29
|
-
export type RequestOptions<T> = {
|
|
30
|
-
// disable data fetching
|
|
31
|
-
disabled?: boolean;
|
|
32
|
-
initialData?: T;
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Makes a GET request with SWR.
|
|
37
|
-
*
|
|
38
|
-
* @param url The request URL.
|
|
39
|
-
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
|
|
40
|
-
* @returns SWR response
|
|
41
|
-
*/
|
|
42
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
43
|
-
export function get<Result, Error = any>(
|
|
44
|
-
url: string | null,
|
|
45
|
-
args?: unknown,
|
|
46
|
-
options?: RequestOptions<Result>
|
|
47
|
-
): SWRResponse<Result, Error> {
|
|
48
|
-
const reqUrl = options?.disabled ? null : url ? makeUrl(url, args) : null;
|
|
49
|
-
return useSWR<Result, Error>(reqUrl, fetcher, {
|
|
50
|
-
fallbackData: options?.initialData,
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Makes a POST request.
|
|
56
|
-
*
|
|
57
|
-
* @param url The request URL.
|
|
58
|
-
* @param data The request data.
|
|
59
|
-
* @param mutate Mutator for invalidating cache.
|
|
60
|
-
*/
|
|
61
|
-
export async function post<Result>(url: string, data: unknown, mutate: Mutator): Promise<Result> {
|
|
62
|
-
const r: Result = await fetcher(url, {
|
|
63
|
-
method: 'POST',
|
|
64
|
-
headers: {
|
|
65
|
-
'content-type': 'application/json',
|
|
66
|
-
},
|
|
67
|
-
body: marshal(data),
|
|
68
|
-
});
|
|
69
|
-
mutate();
|
|
70
|
-
return r;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Makes a PUT request.
|
|
75
|
-
*
|
|
76
|
-
* @param url The request URL.
|
|
77
|
-
* @param data The request data.
|
|
78
|
-
* @param mutate Mutator for invalidating cache.
|
|
79
|
-
*/
|
|
80
|
-
export async function put<Result>(url: string, data: unknown, mutate: Mutator): Promise<Result> {
|
|
81
|
-
const r: Result = await fetcher(url, {
|
|
82
|
-
method: 'PUT',
|
|
83
|
-
headers: {
|
|
84
|
-
'content-type': 'application/json',
|
|
85
|
-
},
|
|
86
|
-
body: marshal(data),
|
|
87
|
-
});
|
|
88
|
-
mutate();
|
|
89
|
-
return r;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Makes a DELETE request.
|
|
94
|
-
*
|
|
95
|
-
* @param url The request URL.
|
|
96
|
-
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
|
|
97
|
-
* @param mutate Mutator for invalidating cache.
|
|
98
|
-
*/
|
|
99
|
-
export async function del<Result>(url: string, args: unknown, mutate: Mutator): Promise<Result> {
|
|
100
|
-
const reqUrl = makeUrl(url, args);
|
|
101
|
-
const r: Result = await fetcher(reqUrl, {
|
|
102
|
-
method: 'DELETE',
|
|
103
|
-
});
|
|
104
|
-
const path = url.split('/');
|
|
105
|
-
path.pop();
|
|
106
|
-
mutate();
|
|
107
|
-
return r;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
type Mutator = (
|
|
111
|
-
data?: unknown | Promise<unknown> | MutatorCallback,
|
|
112
|
-
opts?: boolean | MutatorOptions
|
|
113
|
-
) => Promise<unknown[]>;
|
|
114
|
-
|
|
115
|
-
export function getMutate(prefixes: string[]): Mutator {
|
|
116
|
-
// https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys-from-regex
|
|
117
|
-
const { cache, mutate } = useSWRConfig();
|
|
118
|
-
return (data?: unknown | Promise<unknown> | MutatorCallback, opts?: boolean | MutatorOptions) => {
|
|
119
|
-
if (!(cache instanceof Map)) {
|
|
120
|
-
throw new Error('mutate requires the cache provider to be a Map instance');
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const keys = Array.from(cache.keys()).filter(
|
|
124
|
-
(k) => typeof k === 'string' && prefixes.some((prefix) => k.startsWith(prefix))
|
|
125
|
-
) as string[];
|
|
126
|
-
const mutations = keys.map((key) => mutate(key, data, opts));
|
|
127
|
-
return Promise.all(mutations);
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export async function fetcher<R>(url: string, options?: RequestInit) {
|
|
132
|
-
const res = await fetch(url, options);
|
|
133
|
-
if (!res.ok) {
|
|
134
|
-
const error: Error & { info?: unknown; status?: number } = new Error(
|
|
135
|
-
'An error occurred while fetching the data.'
|
|
136
|
-
);
|
|
137
|
-
error.info = unmarshal(await res.text());
|
|
138
|
-
error.status = res.status;
|
|
139
|
-
throw error;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
const textResult = await res.text();
|
|
143
|
-
try {
|
|
144
|
-
return unmarshal(textResult) as R;
|
|
145
|
-
} catch (err) {
|
|
146
|
-
console.error(`Unable to deserialize data:`, textResult);
|
|
147
|
-
throw err;
|
|
148
|
-
}
|
|
149
|
-
}
|
package/res/marshal-json.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
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
|
-
}
|
package/res/marshal-superjson.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
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
|
-
}
|