@zenstackhq/tanstack-query 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 +21 -0
- package/README.md +5 -0
- package/generator.d.ts +4 -0
- package/generator.js +376 -0
- package/generator.js.map +1 -0
- package/index.d.ts +5 -0
- package/index.js +21 -0
- package/index.js.map +1 -0
- package/package.json +54 -0
- package/res/marshal-json.ts +12 -0
- package/res/marshal-superjson.ts +20 -0
- package/res/react/helper.ts +148 -0
- package/res/shared.ts +36 -0
- package/res/svelte/helper.ts +140 -0
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
package/generator.d.ts
ADDED
package/generator.js
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
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 ts_morph_1 = require("ts-morph");
|
|
22
|
+
const upper_case_first_1 = require("upper-case-first");
|
|
23
|
+
const _1 = require(".");
|
|
24
|
+
const supportedTargets = ['react', 'svelte'];
|
|
25
|
+
function generate(model, options, dmmf) {
|
|
26
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
27
|
+
let outDir = (0, sdk_1.requireOption)(options, 'output');
|
|
28
|
+
outDir = (0, sdk_1.resolvePath)(outDir, options);
|
|
29
|
+
const project = (0, sdk_1.createProject)();
|
|
30
|
+
const warnings = [];
|
|
31
|
+
const models = (0, sdk_1.getDataModels)(model);
|
|
32
|
+
const target = (0, sdk_1.requireOption)(options, 'target');
|
|
33
|
+
if (!supportedTargets.includes(target)) {
|
|
34
|
+
throw new sdk_1.PluginError(options.name, `Unsupported target "${target}", supported values: ${supportedTargets.join(', ')}`);
|
|
35
|
+
}
|
|
36
|
+
generateIndex(project, outDir, models);
|
|
37
|
+
generateHelper(target, project, outDir, options.useSuperJson === true);
|
|
38
|
+
models.forEach((dataModel) => {
|
|
39
|
+
const mapping = dmmf.mappings.modelOperations.find((op) => op.model === dataModel.name);
|
|
40
|
+
if (!mapping) {
|
|
41
|
+
warnings.push(`Unable to find mapping for model ${dataModel.name}`);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
generateModelHooks(target, project, outDir, dataModel, mapping);
|
|
45
|
+
});
|
|
46
|
+
yield (0, sdk_1.saveProject)(project);
|
|
47
|
+
return warnings;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
exports.generate = generate;
|
|
51
|
+
function generateQueryHook(target, sf, model, operation, returnArray, optionalInput, overrideReturnType, overrideInputType, overrideTypeParameters) {
|
|
52
|
+
const capOperation = (0, upper_case_first_1.upperCaseFirst)(operation);
|
|
53
|
+
const argsType = overrideInputType !== null && overrideInputType !== void 0 ? overrideInputType : `Prisma.${model}${capOperation}Args`;
|
|
54
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
55
|
+
const returnType = overrideReturnType !== null && overrideReturnType !== void 0 ? overrideReturnType : (returnArray ? `Array<Prisma.${model}GetPayload<T>>` : `Prisma.${model}GetPayload<T>`);
|
|
56
|
+
const optionsType = makeQueryOptions(target, returnType);
|
|
57
|
+
const func = sf.addFunction({
|
|
58
|
+
name: `use${capOperation}${model}`,
|
|
59
|
+
typeParameters: overrideTypeParameters !== null && overrideTypeParameters !== void 0 ? overrideTypeParameters : [`T extends ${argsType}`],
|
|
60
|
+
parameters: [
|
|
61
|
+
{
|
|
62
|
+
name: optionalInput ? 'args?' : 'args',
|
|
63
|
+
type: inputType,
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: 'options?',
|
|
67
|
+
type: optionsType,
|
|
68
|
+
},
|
|
69
|
+
],
|
|
70
|
+
isExported: true,
|
|
71
|
+
});
|
|
72
|
+
func.addStatements([
|
|
73
|
+
makeGetContext(target),
|
|
74
|
+
`return query<${returnType}>('${model}', \`\${endpoint}/${(0, lower_case_first_1.lowerCaseFirst)(model)}/${operation}\`, args, options);`,
|
|
75
|
+
]);
|
|
76
|
+
}
|
|
77
|
+
function generateMutationHook(target, sf, model, operation, httpVerb, overrideReturnType) {
|
|
78
|
+
const capOperation = (0, upper_case_first_1.upperCaseFirst)(operation);
|
|
79
|
+
const argsType = `Prisma.${model}${capOperation}Args`;
|
|
80
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
81
|
+
const returnType = overrideReturnType !== null && overrideReturnType !== void 0 ? overrideReturnType : `Prisma.CheckSelect<T, ${model}, Prisma.${model}GetPayload<T>>`;
|
|
82
|
+
const nonGenericOptionsType = `Omit<${makeMutationOptions(target, overrideReturnType !== null && overrideReturnType !== void 0 ? overrideReturnType : model, argsType)}, 'mutationFn'>`;
|
|
83
|
+
const optionsType = `Omit<${makeMutationOptions(target, returnType, inputType)}, 'mutationFn'>`;
|
|
84
|
+
const func = sf.addFunction({
|
|
85
|
+
name: `use${capOperation}${model}`,
|
|
86
|
+
isExported: true,
|
|
87
|
+
parameters: [
|
|
88
|
+
{
|
|
89
|
+
name: 'options?',
|
|
90
|
+
type: nonGenericOptionsType,
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
name: 'invalidateQueries',
|
|
94
|
+
type: 'boolean',
|
|
95
|
+
initializer: 'true',
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
});
|
|
99
|
+
// get endpoint from context
|
|
100
|
+
func.addStatements([makeGetContext(target)]);
|
|
101
|
+
func.addVariableStatement({
|
|
102
|
+
declarationKind: ts_morph_1.VariableDeclarationKind.Const,
|
|
103
|
+
declarations: [
|
|
104
|
+
{
|
|
105
|
+
name: `_mutation`,
|
|
106
|
+
initializer: `
|
|
107
|
+
${httpVerb}Mutation<${argsType}, ${overrideReturnType !== null && overrideReturnType !== void 0 ? overrideReturnType : model}>('${model}', \`\${endpoint}/${(0, lower_case_first_1.lowerCaseFirst)(model)}/${operation}\`, options, invalidateQueries)
|
|
108
|
+
`,
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
});
|
|
112
|
+
switch (target) {
|
|
113
|
+
case 'react':
|
|
114
|
+
// override the mutateAsync function to return the correct type
|
|
115
|
+
func.addVariableStatement({
|
|
116
|
+
declarationKind: ts_morph_1.VariableDeclarationKind.Const,
|
|
117
|
+
declarations: [
|
|
118
|
+
{
|
|
119
|
+
name: 'mutation',
|
|
120
|
+
initializer: `{
|
|
121
|
+
..._mutation,
|
|
122
|
+
async mutateAsync<T extends ${argsType}>(
|
|
123
|
+
args: Prisma.SelectSubset<T, ${argsType}>,
|
|
124
|
+
options?: ${optionsType}
|
|
125
|
+
) {
|
|
126
|
+
return (await _mutation.mutateAsync(
|
|
127
|
+
args,
|
|
128
|
+
options as any
|
|
129
|
+
)) as ${returnType};
|
|
130
|
+
},
|
|
131
|
+
}`,
|
|
132
|
+
},
|
|
133
|
+
],
|
|
134
|
+
});
|
|
135
|
+
break;
|
|
136
|
+
case 'svelte':
|
|
137
|
+
// svelte-query returns a store for mutations
|
|
138
|
+
// here we override the mutateAsync function to return the correct type
|
|
139
|
+
// and call `derived` to return a new reactive store
|
|
140
|
+
func.addVariableStatement({
|
|
141
|
+
declarationKind: ts_morph_1.VariableDeclarationKind.Const,
|
|
142
|
+
declarations: [
|
|
143
|
+
{
|
|
144
|
+
name: 'mutation',
|
|
145
|
+
initializer: `derived(_mutation, value => ({
|
|
146
|
+
...value,
|
|
147
|
+
async mutateAsync<T extends ${argsType}>(
|
|
148
|
+
args: Prisma.SelectSubset<T, ${argsType}>,
|
|
149
|
+
options?: ${optionsType}
|
|
150
|
+
) {
|
|
151
|
+
return (await value.mutateAsync(
|
|
152
|
+
args,
|
|
153
|
+
options as any
|
|
154
|
+
)) as ${returnType};
|
|
155
|
+
},
|
|
156
|
+
}))`,
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
});
|
|
160
|
+
break;
|
|
161
|
+
default:
|
|
162
|
+
throw new sdk_1.PluginError(_1.name, `Unsupported target "${target}"`);
|
|
163
|
+
}
|
|
164
|
+
func.addStatements('return mutation;');
|
|
165
|
+
}
|
|
166
|
+
function generateModelHooks(target, project, outDir, model, mapping) {
|
|
167
|
+
const fileName = (0, change_case_1.paramCase)(model.name);
|
|
168
|
+
const sf = project.createSourceFile(path_1.default.join(outDir, `${fileName}.ts`), undefined, { overwrite: true });
|
|
169
|
+
sf.addStatements('/* eslint-disable */');
|
|
170
|
+
sf.addImportDeclaration({
|
|
171
|
+
namedImports: ['Prisma', model.name],
|
|
172
|
+
isTypeOnly: true,
|
|
173
|
+
moduleSpecifier: '@prisma/client',
|
|
174
|
+
});
|
|
175
|
+
sf.addStatements(makeBaseImports(target));
|
|
176
|
+
// create is somehow named "createOne" in the DMMF
|
|
177
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
178
|
+
if (mapping.create || mapping.createOne) {
|
|
179
|
+
generateMutationHook(target, sf, model.name, 'create', 'post');
|
|
180
|
+
}
|
|
181
|
+
// createMany
|
|
182
|
+
if (mapping.createMany) {
|
|
183
|
+
generateMutationHook(target, sf, model.name, 'createMany', 'post', 'Prisma.BatchPayload');
|
|
184
|
+
}
|
|
185
|
+
// findMany
|
|
186
|
+
if (mapping.findMany) {
|
|
187
|
+
generateQueryHook(target, sf, model.name, 'findMany', true, true);
|
|
188
|
+
}
|
|
189
|
+
// findUnique
|
|
190
|
+
if (mapping.findUnique) {
|
|
191
|
+
generateQueryHook(target, sf, model.name, 'findUnique', false, false);
|
|
192
|
+
}
|
|
193
|
+
// findFirst
|
|
194
|
+
if (mapping.findFirst) {
|
|
195
|
+
generateQueryHook(target, sf, model.name, 'findFirst', false, true);
|
|
196
|
+
}
|
|
197
|
+
// update
|
|
198
|
+
// update is somehow named "updateOne" in the DMMF
|
|
199
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
200
|
+
if (mapping.update || mapping.updateOne) {
|
|
201
|
+
generateMutationHook(target, sf, model.name, 'update', 'put');
|
|
202
|
+
}
|
|
203
|
+
// updateMany
|
|
204
|
+
if (mapping.updateMany) {
|
|
205
|
+
generateMutationHook(target, sf, model.name, 'updateMany', 'put', 'Prisma.BatchPayload');
|
|
206
|
+
}
|
|
207
|
+
// upsert
|
|
208
|
+
// upsert is somehow named "upsertOne" in the DMMF
|
|
209
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
210
|
+
if (mapping.upsert || mapping.upsertOne) {
|
|
211
|
+
generateMutationHook(target, sf, model.name, 'upsert', 'post');
|
|
212
|
+
}
|
|
213
|
+
// del
|
|
214
|
+
// delete is somehow named "deleteOne" in the DMMF
|
|
215
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
216
|
+
if (mapping.delete || mapping.deleteOne) {
|
|
217
|
+
generateMutationHook(target, sf, model.name, 'delete', 'delete');
|
|
218
|
+
}
|
|
219
|
+
// deleteMany
|
|
220
|
+
if (mapping.deleteMany) {
|
|
221
|
+
generateMutationHook(target, sf, model.name, 'deleteMany', 'delete', 'Prisma.BatchPayload');
|
|
222
|
+
}
|
|
223
|
+
// aggregate
|
|
224
|
+
if (mapping.aggregate) {
|
|
225
|
+
generateQueryHook(target, sf, model.name, 'aggregate', false, false, `Prisma.Get${model.name}AggregateType<T>`);
|
|
226
|
+
}
|
|
227
|
+
// groupBy
|
|
228
|
+
if (mapping.groupBy) {
|
|
229
|
+
const typeParameters = [
|
|
230
|
+
`T extends Prisma.${model.name}GroupByArgs`,
|
|
231
|
+
`HasSelectOrTake extends Prisma.Or<Prisma.Extends<'skip', Prisma.Keys<T>>, Prisma.Extends<'take', Prisma.Keys<T>>>`,
|
|
232
|
+
`OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.${model.name}GroupByArgs['orderBy'] }: { orderBy?: Prisma.${model.name}GroupByArgs['orderBy'] },`,
|
|
233
|
+
`OrderFields extends Prisma.ExcludeUnderscoreKeys<Prisma.Keys<Prisma.MaybeTupleToUnion<T['orderBy']>>>`,
|
|
234
|
+
`ByFields extends Prisma.TupleToUnion<T['by']>`,
|
|
235
|
+
`ByValid extends Prisma.Has<ByFields, OrderFields>`,
|
|
236
|
+
`HavingFields extends Prisma.GetHavingFields<T['having']>`,
|
|
237
|
+
`HavingValid extends Prisma.Has<ByFields, HavingFields>`,
|
|
238
|
+
`ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False`,
|
|
239
|
+
`InputErrors extends ByEmpty extends Prisma.True
|
|
240
|
+
? \`Error: "by" must not be empty.\`
|
|
241
|
+
: HavingValid extends Prisma.False
|
|
242
|
+
? {
|
|
243
|
+
[P in HavingFields]: P extends ByFields
|
|
244
|
+
? never
|
|
245
|
+
: P extends string
|
|
246
|
+
? \`Error: Field "\${P}" used in "having" needs to be provided in "by".\`
|
|
247
|
+
: [
|
|
248
|
+
Error,
|
|
249
|
+
'Field ',
|
|
250
|
+
P,
|
|
251
|
+
\` in "having" needs to be provided in "by"\`,
|
|
252
|
+
]
|
|
253
|
+
}[HavingFields]
|
|
254
|
+
: 'take' extends Prisma.Keys<T>
|
|
255
|
+
? 'orderBy' extends Prisma.Keys<T>
|
|
256
|
+
? ByValid extends Prisma.True
|
|
257
|
+
? {}
|
|
258
|
+
: {
|
|
259
|
+
[P in OrderFields]: P extends ByFields
|
|
260
|
+
? never
|
|
261
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
262
|
+
}[OrderFields]
|
|
263
|
+
: 'Error: If you provide "take", you also need to provide "orderBy"'
|
|
264
|
+
: 'skip' extends Prisma.Keys<T>
|
|
265
|
+
? 'orderBy' extends Prisma.Keys<T>
|
|
266
|
+
? ByValid extends Prisma.True
|
|
267
|
+
? {}
|
|
268
|
+
: {
|
|
269
|
+
[P in OrderFields]: P extends ByFields
|
|
270
|
+
? never
|
|
271
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
272
|
+
}[OrderFields]
|
|
273
|
+
: 'Error: If you provide "skip", you also need to provide "orderBy"'
|
|
274
|
+
: ByValid extends Prisma.True
|
|
275
|
+
? {}
|
|
276
|
+
: {
|
|
277
|
+
[P in OrderFields]: P extends ByFields
|
|
278
|
+
? never
|
|
279
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
280
|
+
}[OrderFields]`,
|
|
281
|
+
];
|
|
282
|
+
const returnType = `{} extends InputErrors ?
|
|
283
|
+
Array<Prisma.PickArray<Prisma.${model.name}GroupByOutputType, T['by']> &
|
|
284
|
+
{
|
|
285
|
+
[P in ((keyof T) & (keyof Prisma.${model.name}GroupByOutputType))]: P extends '_count'
|
|
286
|
+
? T[P] extends boolean
|
|
287
|
+
? number
|
|
288
|
+
: Prisma.GetScalarType<T[P], Prisma.${model.name}GroupByOutputType[P]>
|
|
289
|
+
: Prisma.GetScalarType<T[P], Prisma.${model.name}GroupByOutputType[P]>
|
|
290
|
+
}
|
|
291
|
+
> : InputErrors`;
|
|
292
|
+
generateQueryHook(target, sf, model.name, 'groupBy', false, false, returnType, `Prisma.SubsetIntersection<T, Prisma.${model.name}GroupByArgs, OrderByArg> & InputErrors`, typeParameters);
|
|
293
|
+
}
|
|
294
|
+
// somehow dmmf doesn't contain "count" operation, so we unconditionally add it here
|
|
295
|
+
{
|
|
296
|
+
generateQueryHook(target, sf, model.name, 'count', false, true, `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType<T['select'], Prisma.${model.name}CountAggregateOutputType> : number`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function generateIndex(project, outDir, models) {
|
|
300
|
+
const sf = project.createSourceFile(path_1.default.join(outDir, 'index.ts'), undefined, { overwrite: true });
|
|
301
|
+
sf.addStatements(models.map((d) => `export * from './${(0, change_case_1.paramCase)(d.name)}';`));
|
|
302
|
+
sf.addStatements(`export * from './_helper';`);
|
|
303
|
+
}
|
|
304
|
+
function generateHelper(target, project, outDir, useSuperJson) {
|
|
305
|
+
let srcFile;
|
|
306
|
+
switch (target) {
|
|
307
|
+
case 'react':
|
|
308
|
+
srcFile = path_1.default.join(__dirname, './res/react/helper.ts');
|
|
309
|
+
break;
|
|
310
|
+
case 'svelte':
|
|
311
|
+
srcFile = path_1.default.join(__dirname, './res/svelte/helper.ts');
|
|
312
|
+
break;
|
|
313
|
+
default:
|
|
314
|
+
throw new sdk_1.PluginError(_1.name, `Unsupported target: ${target}`);
|
|
315
|
+
}
|
|
316
|
+
// merge content of `shared.ts`, `helper.ts` and `marshal-?.ts`
|
|
317
|
+
const sharedContent = fs_1.default.readFileSync(path_1.default.join(__dirname, './res/shared.ts'), 'utf-8');
|
|
318
|
+
const helperContent = fs_1.default.readFileSync(srcFile, 'utf-8');
|
|
319
|
+
const marshalContent = fs_1.default.readFileSync(path_1.default.join(__dirname, useSuperJson ? './res/marshal-superjson.ts' : './res/marshal-json.ts'), 'utf-8');
|
|
320
|
+
project.createSourceFile(path_1.default.join(outDir, '_helper.ts'), `${sharedContent}\n${helperContent}\n${marshalContent}`, {
|
|
321
|
+
overwrite: true,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
function makeGetContext(target) {
|
|
325
|
+
switch (target) {
|
|
326
|
+
case 'react':
|
|
327
|
+
return 'const { endpoint } = useContext(RequestHandlerContext);';
|
|
328
|
+
case 'svelte':
|
|
329
|
+
return `const { endpoint } = getContext<RequestHandlerContext>(SvelteQueryContextKey);`;
|
|
330
|
+
default:
|
|
331
|
+
throw new sdk_1.PluginError(_1.name, `Unsupported target "${target}"`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
function makeBaseImports(target) {
|
|
335
|
+
const shared = [`import { query, postMutation, putMutation, deleteMutation } from './_helper';`];
|
|
336
|
+
switch (target) {
|
|
337
|
+
case 'react':
|
|
338
|
+
return [
|
|
339
|
+
`import { useContext } from 'react';`,
|
|
340
|
+
`import type { UseMutationOptions, UseQueryOptions } from '@tanstack/react-query';`,
|
|
341
|
+
`import { RequestHandlerContext } from './_helper';`,
|
|
342
|
+
...shared,
|
|
343
|
+
];
|
|
344
|
+
case 'svelte':
|
|
345
|
+
return [
|
|
346
|
+
`import { getContext } from 'svelte';`,
|
|
347
|
+
`import { derived } from 'svelte/store';`,
|
|
348
|
+
`import type { MutationOptions, QueryOptions } from '@tanstack/svelte-query';`,
|
|
349
|
+
`import { SvelteQueryContextKey, type RequestHandlerContext } from './_helper';`,
|
|
350
|
+
...shared,
|
|
351
|
+
];
|
|
352
|
+
default:
|
|
353
|
+
throw new sdk_1.PluginError(_1.name, `Unsupported target: ${target}`);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function makeQueryOptions(target, returnType) {
|
|
357
|
+
switch (target) {
|
|
358
|
+
case 'react':
|
|
359
|
+
return `UseQueryOptions<${returnType}>`;
|
|
360
|
+
case 'svelte':
|
|
361
|
+
return `QueryOptions<${returnType}>`;
|
|
362
|
+
default:
|
|
363
|
+
throw new sdk_1.PluginError(_1.name, `Unsupported target: ${target}`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function makeMutationOptions(target, returnType, argsType) {
|
|
367
|
+
switch (target) {
|
|
368
|
+
case 'react':
|
|
369
|
+
return `UseMutationOptions<${returnType}, unknown, ${argsType}>`;
|
|
370
|
+
case 'svelte':
|
|
371
|
+
return `MutationOptions<${returnType}, unknown, ${argsType}>`;
|
|
372
|
+
default:
|
|
373
|
+
throw new sdk_1.PluginError(_1.name, `Unsupported target: ${target}`);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
//# sourceMappingURL=generator.js.map
|
package/generator.js.map
AD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,CAAC,OAAI,EAAE,uBAAuB,MAAM,EAAE,CAAC,CAAC;KACpE;AACL,CAAC"}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { DMMF } from '@prisma/generator-helper';
|
|
2
|
+
import type { PluginOptions } from '@zenstackhq/sdk';
|
|
3
|
+
import type { Model } from '@zenstackhq/sdk/ast';
|
|
4
|
+
export declare const name = "Tanstack Query";
|
|
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 = 'Tanstack Query';
|
|
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,gBAAgB,CAAC;AAErC,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,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zenstackhq/tanstack-query",
|
|
3
|
+
"displayName": "ZenStack plugin for generating tanstack-query hooks",
|
|
4
|
+
"version": "1.0.0-alpha.119",
|
|
5
|
+
"description": "ZenStack plugin for generating tanstack-query 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.29.7",
|
|
30
|
+
"@tanstack/svelte-query": "^4.29.7",
|
|
31
|
+
"@types/jest": "^29.5.0",
|
|
32
|
+
"@types/lower-case-first": "^1.0.1",
|
|
33
|
+
"@types/react": "^18.0.26",
|
|
34
|
+
"@types/tmp": "^0.2.3",
|
|
35
|
+
"@types/upper-case-first": "^1.1.2",
|
|
36
|
+
"copyfiles": "^2.4.1",
|
|
37
|
+
"jest": "^29.5.0",
|
|
38
|
+
"react": "^17.0.2 || ^18",
|
|
39
|
+
"react-dom": "^17.0.2 || ^18",
|
|
40
|
+
"rimraf": "^3.0.2",
|
|
41
|
+
"swr": "^2.0.3",
|
|
42
|
+
"ts-jest": "^29.0.5",
|
|
43
|
+
"typescript": "^4.9.4",
|
|
44
|
+
"@zenstackhq/testtools": "1.0.0-alpha.119"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"clean": "rimraf dist",
|
|
48
|
+
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist",
|
|
49
|
+
"watch": "tsc --watch",
|
|
50
|
+
"lint": "eslint src --ext ts",
|
|
51
|
+
"test": "jest",
|
|
52
|
+
"publish-dev": "pnpm publish --tag dev"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
useMutation,
|
|
5
|
+
useQuery,
|
|
6
|
+
useQueryClient,
|
|
7
|
+
type MutateFunction,
|
|
8
|
+
type QueryClient,
|
|
9
|
+
type UseMutationOptions,
|
|
10
|
+
type UseQueryOptions,
|
|
11
|
+
} from '@tanstack/react-query';
|
|
12
|
+
import { createContext } from 'react';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Context for configuring react hooks.
|
|
16
|
+
*/
|
|
17
|
+
export const RequestHandlerContext = createContext<RequestHandlerContext>({
|
|
18
|
+
endpoint: DEFAULT_QUERY_ENDPOINT,
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Context provider.
|
|
23
|
+
*/
|
|
24
|
+
export const Provider = RequestHandlerContext.Provider;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Creates a react-query query.
|
|
28
|
+
*
|
|
29
|
+
* @param model The name of the model under query.
|
|
30
|
+
* @param url The request URL.
|
|
31
|
+
* @param args The request args object, URL-encoded and appended as "?q=" parameter
|
|
32
|
+
* @param options The react-query options object
|
|
33
|
+
* @returns useQuery hook
|
|
34
|
+
*/
|
|
35
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
36
|
+
export function query<R>(model: string, url: string, args?: unknown, options?: UseQueryOptions<R>) {
|
|
37
|
+
const reqUrl = makeUrl(url, args);
|
|
38
|
+
return useQuery<R>({
|
|
39
|
+
queryKey: [QUERY_KEY_PREFIX + model, url, args],
|
|
40
|
+
queryFn: () => fetcher<R>(reqUrl),
|
|
41
|
+
...options,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Creates a POST mutation with react-query.
|
|
47
|
+
*
|
|
48
|
+
* @param model The name of the model under mutation.
|
|
49
|
+
* @param url The request URL.
|
|
50
|
+
* @param options The react-query options.
|
|
51
|
+
* @param invalidateQueries Whether to invalidate queries after mutation.
|
|
52
|
+
* @returns useMutation hooks
|
|
53
|
+
*/
|
|
54
|
+
export function postMutation<T, R = any>(
|
|
55
|
+
model: string,
|
|
56
|
+
url: string,
|
|
57
|
+
options?: Omit<UseMutationOptions<R, unknown, T>, 'mutationFn'>,
|
|
58
|
+
invalidateQueries = true
|
|
59
|
+
) {
|
|
60
|
+
const queryClient = useQueryClient();
|
|
61
|
+
const mutationFn = (data: any) =>
|
|
62
|
+
fetcher<R>(url, {
|
|
63
|
+
method: 'POST',
|
|
64
|
+
headers: {
|
|
65
|
+
'content-type': 'application/json',
|
|
66
|
+
},
|
|
67
|
+
body: marshal(data),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
|
|
71
|
+
const mutation = useMutation<R, unknown, T>(finalOptions);
|
|
72
|
+
return mutation;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Creates a PUT mutation with react-query.
|
|
77
|
+
*
|
|
78
|
+
* @param model The name of the model under mutation.
|
|
79
|
+
* @param url The request URL.
|
|
80
|
+
* @param options The react-query options.
|
|
81
|
+
* @param invalidateQueries Whether to invalidate queries after mutation.
|
|
82
|
+
* @returns useMutation hooks
|
|
83
|
+
*/
|
|
84
|
+
export function putMutation<T, R = any>(
|
|
85
|
+
model: string,
|
|
86
|
+
url: string,
|
|
87
|
+
options?: Omit<UseMutationOptions<R, unknown, T>, 'mutationFn'>,
|
|
88
|
+
invalidateQueries = true
|
|
89
|
+
) {
|
|
90
|
+
const queryClient = useQueryClient();
|
|
91
|
+
const mutationFn = (data: any) =>
|
|
92
|
+
fetcher<R>(url, {
|
|
93
|
+
method: 'PUT',
|
|
94
|
+
headers: {
|
|
95
|
+
'content-type': 'application/json',
|
|
96
|
+
},
|
|
97
|
+
body: marshal(data),
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
|
|
101
|
+
const mutation = useMutation<R, unknown, T>(finalOptions);
|
|
102
|
+
return mutation;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Creates a DELETE mutation with react-query.
|
|
107
|
+
*
|
|
108
|
+
* @param model The name of the model under mutation.
|
|
109
|
+
* @param url The request URL.
|
|
110
|
+
* @param options The react-query options.
|
|
111
|
+
* @param invalidateQueries Whether to invalidate queries after mutation.
|
|
112
|
+
* @returns useMutation hooks
|
|
113
|
+
*/
|
|
114
|
+
export function deleteMutation<T, R = any>(
|
|
115
|
+
model: string,
|
|
116
|
+
url: string,
|
|
117
|
+
options?: Omit<UseMutationOptions<R, unknown, T>, 'mutationFn'>,
|
|
118
|
+
invalidateQueries = true
|
|
119
|
+
) {
|
|
120
|
+
const queryClient = useQueryClient();
|
|
121
|
+
const mutationFn = (data: any) =>
|
|
122
|
+
fetcher<R>(makeUrl(url, data), {
|
|
123
|
+
method: 'DELETE',
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
|
|
127
|
+
const mutation = useMutation<R, unknown, T>(finalOptions);
|
|
128
|
+
return mutation;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function mergeOptions<T, R = any>(
|
|
132
|
+
model: string,
|
|
133
|
+
options: Omit<UseMutationOptions<R, unknown, T, unknown>, 'mutationFn'> | undefined,
|
|
134
|
+
invalidateQueries: boolean,
|
|
135
|
+
mutationFn: MutateFunction<R, unknown, T>,
|
|
136
|
+
queryClient: QueryClient
|
|
137
|
+
): UseMutationOptions<R, unknown, T, unknown> {
|
|
138
|
+
const result = { ...options, mutationFn };
|
|
139
|
+
if (options?.onSuccess || invalidateQueries) {
|
|
140
|
+
result.onSuccess = (...args) => {
|
|
141
|
+
if (invalidateQueries) {
|
|
142
|
+
queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]);
|
|
143
|
+
}
|
|
144
|
+
return options?.onSuccess?.(...args);
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
return result;
|
|
148
|
+
}
|
package/res/shared.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The default query endpoint.
|
|
3
|
+
*/
|
|
4
|
+
export const DEFAULT_QUERY_ENDPOINT = '/api/model';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Prefix for react-query keys.
|
|
8
|
+
*/
|
|
9
|
+
export const QUERY_KEY_PREFIX = 'zenstack:';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Context type for configuring the hooks.
|
|
13
|
+
*/
|
|
14
|
+
export type RequestHandlerContext = {
|
|
15
|
+
endpoint: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
async function fetcher<R>(url: string, options?: RequestInit) {
|
|
19
|
+
const res = await fetch(url, options);
|
|
20
|
+
if (!res.ok) {
|
|
21
|
+
const error: Error & { info?: unknown; status?: number } = new Error(
|
|
22
|
+
'An error occurred while fetching the data.'
|
|
23
|
+
);
|
|
24
|
+
error.info = unmarshal(await res.text());
|
|
25
|
+
error.status = res.status;
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const textResult = await res.text();
|
|
30
|
+
try {
|
|
31
|
+
return unmarshal(textResult) as R;
|
|
32
|
+
} catch (err) {
|
|
33
|
+
console.error(`Unable to deserialize data:`, textResult);
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
createMutation,
|
|
5
|
+
createQuery,
|
|
6
|
+
useQueryClient,
|
|
7
|
+
type MutateFunction,
|
|
8
|
+
type MutationOptions,
|
|
9
|
+
type QueryClient,
|
|
10
|
+
type QueryOptions,
|
|
11
|
+
} from '@tanstack/svelte-query';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Key for setting and getting the global query context.
|
|
15
|
+
*/
|
|
16
|
+
export const SvelteQueryContextKey = 'zenstack-svelte-query-context';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Creates a svelte-query query.
|
|
20
|
+
*
|
|
21
|
+
* @param model The name of the model under query.
|
|
22
|
+
* @param url The request URL.
|
|
23
|
+
* @param args The request args object, URL-encoded and appended as "?q=" parameter
|
|
24
|
+
* @param options The svelte-query options object
|
|
25
|
+
* @returns useQuery hook
|
|
26
|
+
*/
|
|
27
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
28
|
+
export function query<R>(model: string, url: string, args?: unknown, options?: QueryOptions<R>) {
|
|
29
|
+
const reqUrl = makeUrl(url, args);
|
|
30
|
+
return createQuery<R>({
|
|
31
|
+
queryKey: [QUERY_KEY_PREFIX + model, url, args],
|
|
32
|
+
queryFn: () => fetcher<R>(reqUrl),
|
|
33
|
+
...options,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Creates a POST mutation with svelte-query.
|
|
39
|
+
*
|
|
40
|
+
* @param model The name of the model under mutation.
|
|
41
|
+
* @param url The request URL.
|
|
42
|
+
* @param options The svelte-query options.
|
|
43
|
+
* @param invalidateQueries Whether to invalidate queries after mutation.
|
|
44
|
+
* @returns useMutation hooks
|
|
45
|
+
*/
|
|
46
|
+
export function postMutation<T, R = any>(
|
|
47
|
+
model: string,
|
|
48
|
+
url: string,
|
|
49
|
+
options?: Omit<MutationOptions<R, unknown, T>, 'mutationFn'>,
|
|
50
|
+
invalidateQueries = true
|
|
51
|
+
) {
|
|
52
|
+
const queryClient = useQueryClient();
|
|
53
|
+
const mutationFn = (data: any) =>
|
|
54
|
+
fetcher<R>(url, {
|
|
55
|
+
method: 'POST',
|
|
56
|
+
headers: {
|
|
57
|
+
'content-type': 'application/json',
|
|
58
|
+
},
|
|
59
|
+
body: marshal(data),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
|
|
63
|
+
const mutation = createMutation<R, unknown, T>(finalOptions);
|
|
64
|
+
return mutation;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Creates a PUT mutation with svelte-query.
|
|
69
|
+
*
|
|
70
|
+
* @param model The name of the model under mutation.
|
|
71
|
+
* @param url The request URL.
|
|
72
|
+
* @param options The svelte-query options.
|
|
73
|
+
* @param invalidateQueries Whether to invalidate queries after mutation.
|
|
74
|
+
* @returns useMutation hooks
|
|
75
|
+
*/
|
|
76
|
+
export function putMutation<T, R = any>(
|
|
77
|
+
model: string,
|
|
78
|
+
url: string,
|
|
79
|
+
options?: Omit<MutationOptions<R, unknown, T>, 'mutationFn'>,
|
|
80
|
+
invalidateQueries = true
|
|
81
|
+
) {
|
|
82
|
+
const queryClient = useQueryClient();
|
|
83
|
+
const mutationFn = (data: any) =>
|
|
84
|
+
fetcher<R>(url, {
|
|
85
|
+
method: 'PUT',
|
|
86
|
+
headers: {
|
|
87
|
+
'content-type': 'application/json',
|
|
88
|
+
},
|
|
89
|
+
body: marshal(data),
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
|
|
93
|
+
const mutation = createMutation<R, unknown, T>(finalOptions);
|
|
94
|
+
return mutation;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Creates a DELETE mutation with svelte-query.
|
|
99
|
+
*
|
|
100
|
+
* @param model The name of the model under mutation.
|
|
101
|
+
* @param url The request URL.
|
|
102
|
+
* @param options The svelte-query options.
|
|
103
|
+
* @param invalidateQueries Whether to invalidate queries after mutation.
|
|
104
|
+
* @returns useMutation hooks
|
|
105
|
+
*/
|
|
106
|
+
export function deleteMutation<T, R = any>(
|
|
107
|
+
model: string,
|
|
108
|
+
url: string,
|
|
109
|
+
options?: Omit<MutationOptions<R, unknown, T>, 'mutationFn'>,
|
|
110
|
+
invalidateQueries = true
|
|
111
|
+
) {
|
|
112
|
+
const queryClient = useQueryClient();
|
|
113
|
+
const mutationFn = (data: any) =>
|
|
114
|
+
fetcher<R>(makeUrl(url, data), {
|
|
115
|
+
method: 'DELETE',
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
|
|
119
|
+
const mutation = createMutation<R, unknown, T>(finalOptions);
|
|
120
|
+
return mutation;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function mergeOptions<T, R = any>(
|
|
124
|
+
model: string,
|
|
125
|
+
options: Omit<MutationOptions<R, unknown, T, unknown>, 'mutationFn'> | undefined,
|
|
126
|
+
invalidateQueries: boolean,
|
|
127
|
+
mutationFn: MutateFunction<R, unknown, T>,
|
|
128
|
+
queryClient: QueryClient
|
|
129
|
+
): MutationOptions<R, unknown, T, unknown> {
|
|
130
|
+
const result = { ...options, mutationFn };
|
|
131
|
+
if (options?.onSuccess || invalidateQueries) {
|
|
132
|
+
result.onSuccess = (...args) => {
|
|
133
|
+
if (invalidateQueries) {
|
|
134
|
+
queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]);
|
|
135
|
+
}
|
|
136
|
+
return options?.onSuccess?.(...args);
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|