@zenstackhq/tanstack-query 1.0.1 → 1.1.0
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.js +17 -2
- package/generator.js.map +1 -1
- package/package.json +16 -6
- package/runtime/{common-52ab2c3a.d.ts → common-83308e88.d.ts} +1 -1
- package/runtime/index.d.mts +2 -0
- package/runtime/index.d.ts +2 -0
- package/runtime/index.js.map +1 -1
- package/runtime/react.d.mts +1 -1
- package/runtime/react.d.ts +1 -1
- package/runtime/react.js +23 -12
- package/runtime/react.js.map +1 -1
- package/runtime/react.mjs +14 -13
- package/runtime/react.mjs.map +1 -1
- package/runtime/svelte.d.mts +6 -3
- package/runtime/svelte.d.ts +6 -3
- package/runtime/svelte.js +31 -14
- package/runtime/svelte.js.map +1 -1
- package/runtime/svelte.mjs +20 -14
- package/runtime/svelte.mjs.map +1 -1
- package/runtime/vue.d.mts +62 -0
- package/runtime/vue.d.ts +62 -0
- package/runtime/vue.js +244 -0
- package/runtime/vue.js.map +1 -0
- package/runtime/vue.mjs +210 -0
- package/runtime/vue.mjs.map +1 -0
package/generator.js
CHANGED
|
@@ -21,7 +21,7 @@ const semver_1 = __importDefault(require("semver"));
|
|
|
21
21
|
const ts_morph_1 = require("ts-morph");
|
|
22
22
|
const upper_case_first_1 = require("upper-case-first");
|
|
23
23
|
const _1 = require(".");
|
|
24
|
-
const supportedTargets = ['react', 'svelte'];
|
|
24
|
+
const supportedTargets = ['react', 'vue', 'svelte'];
|
|
25
25
|
function generate(model, options, dmmf) {
|
|
26
26
|
return __awaiter(this, void 0, void 0, function* () {
|
|
27
27
|
let outDir = (0, sdk_1.requireOption)(options, 'output');
|
|
@@ -113,6 +113,7 @@ function generateMutationHook(target, sf, model, operation, httpVerb, checkReadB
|
|
|
113
113
|
});
|
|
114
114
|
switch (target) {
|
|
115
115
|
case 'react':
|
|
116
|
+
case 'vue':
|
|
116
117
|
// override the mutateAsync function to return the correct type
|
|
117
118
|
func.addVariableStatement({
|
|
118
119
|
declarationKind: ts_morph_1.VariableDeclarationKind.Const,
|
|
@@ -316,8 +317,11 @@ function generateIndex(project, outDir, models, target) {
|
|
|
316
317
|
case 'react':
|
|
317
318
|
sf.addStatements(`export { Provider } from '@zenstackhq/tanstack-query/runtime/react';`);
|
|
318
319
|
break;
|
|
320
|
+
case 'vue':
|
|
321
|
+
sf.addStatements(`export { VueQueryContextKey, provideHooksContext } from '@zenstackhq/tanstack-query/runtime/vue';`);
|
|
322
|
+
break;
|
|
319
323
|
case 'svelte':
|
|
320
|
-
sf.addStatements(`export { SvelteQueryContextKey } from '@zenstackhq/tanstack-query/runtime/svelte';`);
|
|
324
|
+
sf.addStatements(`export { SvelteQueryContextKey, setHooksContext } from '@zenstackhq/tanstack-query/runtime/svelte';`);
|
|
321
325
|
break;
|
|
322
326
|
}
|
|
323
327
|
}
|
|
@@ -325,6 +329,8 @@ function makeGetContext(target) {
|
|
|
325
329
|
switch (target) {
|
|
326
330
|
case 'react':
|
|
327
331
|
return 'const { endpoint, fetch } = useContext(RequestHandlerContext);';
|
|
332
|
+
case 'vue':
|
|
333
|
+
return 'const { endpoint, fetch } = getContext();';
|
|
328
334
|
case 'svelte':
|
|
329
335
|
return `const { endpoint, fetch } = getContext<RequestHandlerContext>(SvelteQueryContextKey);`;
|
|
330
336
|
default:
|
|
@@ -344,6 +350,12 @@ function makeBaseImports(target) {
|
|
|
344
350
|
`import { RequestHandlerContext } from '@zenstackhq/tanstack-query/runtime/${target}';`,
|
|
345
351
|
...shared,
|
|
346
352
|
];
|
|
353
|
+
case 'vue':
|
|
354
|
+
return [
|
|
355
|
+
`import type { UseMutationOptions, UseQueryOptions, UseInfiniteQueryOptions } from '@tanstack/vue-query';`,
|
|
356
|
+
`import { getContext } from '@zenstackhq/tanstack-query/runtime/${target}';`,
|
|
357
|
+
...shared,
|
|
358
|
+
];
|
|
347
359
|
case 'svelte':
|
|
348
360
|
return [
|
|
349
361
|
`import { getContext } from 'svelte';`,
|
|
@@ -359,6 +371,7 @@ function makeBaseImports(target) {
|
|
|
359
371
|
function makeQueryOptions(target, returnType, infinite) {
|
|
360
372
|
switch (target) {
|
|
361
373
|
case 'react':
|
|
374
|
+
case 'vue':
|
|
362
375
|
return `Use${infinite ? 'Infinite' : ''}QueryOptions<${returnType}>`;
|
|
363
376
|
case 'svelte':
|
|
364
377
|
return `${infinite ? 'CreateInfinite' : ''}QueryOptions<${returnType}>`;
|
|
@@ -370,6 +383,8 @@ function makeMutationOptions(target, returnType, argsType) {
|
|
|
370
383
|
switch (target) {
|
|
371
384
|
case 'react':
|
|
372
385
|
return `UseMutationOptions<${returnType}, unknown, ${argsType}>`;
|
|
386
|
+
case 'vue':
|
|
387
|
+
return `UseMutationOptions<${returnType}, unknown, ${argsType}, unknown>`;
|
|
373
388
|
case 'svelte':
|
|
374
389
|
return `MutationOptions<${returnType}, unknown, ${argsType}>`;
|
|
375
390
|
default:
|
package/generator.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,yCAUyB;AAEzB,6CAAwC;AACxC,uDAAkD;AAClD,gDAAwB;AACxB,oDAA4B;AAC5B,uCAAwE;AACxE,uDAAkD;AAClD,wBAAyB;AAEzB,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,yCAUyB;AAEzB,6CAAwC;AACxC,uDAAkD;AAClD,gDAAwB;AACxB,oDAA4B;AAC5B,uCAAwE;AACxE,uDAAkD;AAClD,wBAAyB;AAEzB,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AAGpD,SAAsB,QAAQ,CAAC,KAAY,EAAE,OAAsB,EAAE,IA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,OAAO,sBAAsB,UAAU,cAAc,QAAQ,YAAY,CAAC;QAC9E,KAAK,QAAQ;YACT,OAAO,mBAAmB,UAAU,cAAc,QAAQ,GAAG,CAAC;QAClE;YACI,MAAM,IAAI,iBAAW,CAAC,OAAI,EAAE,uBAAuB,MAAM,EAAE,CAAC,CAAC;KACpE;AACL,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zenstackhq/tanstack-query",
|
|
3
3
|
"displayName": "ZenStack plugin for generating tanstack-query hooks",
|
|
4
|
-
"version": "1.0
|
|
4
|
+
"version": "1.1.0",
|
|
5
5
|
"description": "ZenStack plugin for generating tanstack-query hooks",
|
|
6
6
|
"main": "index.js",
|
|
7
7
|
"exports": {
|
|
@@ -23,6 +23,12 @@
|
|
|
23
23
|
"default": "./runtime/react.js",
|
|
24
24
|
"types": "./runtime/react.d.ts"
|
|
25
25
|
},
|
|
26
|
+
"./runtime/vue": {
|
|
27
|
+
"import": "./runtime/vue.mjs",
|
|
28
|
+
"require": "./runtime/vue.js",
|
|
29
|
+
"default": "./runtime/vue.js",
|
|
30
|
+
"types": "./runtime/vue.d.ts"
|
|
31
|
+
},
|
|
26
32
|
"./runtime/svelte": {
|
|
27
33
|
"import": "./runtime/svelte.mjs",
|
|
28
34
|
"require": "./runtime/svelte.js",
|
|
@@ -44,18 +50,20 @@
|
|
|
44
50
|
"dependencies": {
|
|
45
51
|
"@prisma/generator-helper": "^5.0.0",
|
|
46
52
|
"change-case": "^4.1.2",
|
|
53
|
+
"cross-fetch": "^4.0.0",
|
|
47
54
|
"decimal.js": "^10.4.2",
|
|
48
55
|
"lower-case-first": "^2.0.2",
|
|
49
56
|
"semver": "^7.3.8",
|
|
50
57
|
"superjson": "^1.11.0",
|
|
51
58
|
"ts-morph": "^16.0.0",
|
|
52
59
|
"upper-case-first": "^2.0.2",
|
|
53
|
-
"@zenstackhq/runtime": "1.0
|
|
54
|
-
"@zenstackhq/sdk": "1.0
|
|
60
|
+
"@zenstackhq/runtime": "1.1.0",
|
|
61
|
+
"@zenstackhq/sdk": "1.1.0"
|
|
55
62
|
},
|
|
56
63
|
"devDependencies": {
|
|
57
|
-
"@tanstack/react-query": "4.29.7",
|
|
58
|
-
"@tanstack/svelte-query": "4.29.7",
|
|
64
|
+
"@tanstack/react-query": "^4.29.7",
|
|
65
|
+
"@tanstack/svelte-query": "^4.29.7",
|
|
66
|
+
"@tanstack/vue-query": "^4.37.0",
|
|
59
67
|
"@types/jest": "^29.5.0",
|
|
60
68
|
"@types/node": "^18.0.0",
|
|
61
69
|
"@types/react": "18.2.0",
|
|
@@ -65,10 +73,12 @@
|
|
|
65
73
|
"jest": "^29.5.0",
|
|
66
74
|
"react": "18.2.0",
|
|
67
75
|
"rimraf": "^3.0.2",
|
|
76
|
+
"svelte": "^4.2.1",
|
|
68
77
|
"swr": "^2.0.3",
|
|
69
78
|
"ts-jest": "^29.0.5",
|
|
70
79
|
"typescript": "^4.9.4",
|
|
71
|
-
"
|
|
80
|
+
"vue": "^3.3.4",
|
|
81
|
+
"@zenstackhq/testtools": "1.1.0"
|
|
72
82
|
},
|
|
73
83
|
"scripts": {
|
|
74
84
|
"clean": "rimraf dist",
|
package/runtime/index.d.mts
CHANGED
package/runtime/index.d.ts
CHANGED
package/runtime/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/index.ts"],"sourcesContent":["export * from './prisma-types';\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/index.ts"],"sourcesContent":["export * from './prisma-types';\nexport type { FetchFn } from './common';\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
package/runtime/react.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _tanstack_react_query from '@tanstack/react-query';
|
|
2
2
|
import { UseQueryOptions, UseInfiniteQueryOptions, UseMutationOptions } from '@tanstack/react-query';
|
|
3
3
|
import * as react from 'react';
|
|
4
|
-
import { A as APIContext, F as FetchFn } from './common-
|
|
4
|
+
import { A as APIContext, F as FetchFn } from './common-83308e88.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Context for configuring react hooks.
|
package/runtime/react.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _tanstack_react_query from '@tanstack/react-query';
|
|
2
2
|
import { UseQueryOptions, UseInfiniteQueryOptions, UseMutationOptions } from '@tanstack/react-query';
|
|
3
3
|
import * as react from 'react';
|
|
4
|
-
import { A as APIContext, F as FetchFn } from './common-
|
|
4
|
+
import { A as APIContext, F as FetchFn } from './common-83308e88.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Context for configuring react hooks.
|
package/runtime/react.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __defProps = Object.defineProperties;
|
|
4
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
6
|
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
6
7
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
8
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
9
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
10
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
11
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
10
12
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
@@ -32,6 +34,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
32
34
|
}
|
|
33
35
|
return to;
|
|
34
36
|
};
|
|
37
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
38
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
39
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
40
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
41
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
42
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
43
|
+
mod
|
|
44
|
+
));
|
|
35
45
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
36
46
|
var __async = (__this, __arguments, generator) => {
|
|
37
47
|
return new Promise((resolve, reject) => {
|
|
@@ -71,12 +81,13 @@ var import_react = require("react");
|
|
|
71
81
|
|
|
72
82
|
// src/runtime/common.ts
|
|
73
83
|
var import_browser = require("@zenstackhq/runtime/browser");
|
|
84
|
+
var crossFetch = __toESM(require("cross-fetch"));
|
|
74
85
|
var DEFAULT_QUERY_ENDPOINT = "/api/model";
|
|
75
86
|
var QUERY_KEY_PREFIX = "zenstack:";
|
|
76
|
-
function fetcher(url, options,
|
|
87
|
+
function fetcher(url, options, fetch2, checkReadBack) {
|
|
77
88
|
return __async(this, null, function* () {
|
|
78
89
|
var _a, _b, _c;
|
|
79
|
-
const _fetch =
|
|
90
|
+
const _fetch = fetch2 != null ? fetch2 : crossFetch.fetch;
|
|
80
91
|
const res = yield _fetch(url, options);
|
|
81
92
|
if (!res.ok) {
|
|
82
93
|
const errData = unmarshal(yield res.text());
|
|
@@ -135,22 +146,22 @@ var RequestHandlerContext = (0, import_react.createContext)({
|
|
|
135
146
|
fetch: void 0
|
|
136
147
|
});
|
|
137
148
|
var Provider = RequestHandlerContext.Provider;
|
|
138
|
-
function query(model, url, args, options,
|
|
149
|
+
function query(model, url, args, options, fetch2) {
|
|
139
150
|
const reqUrl = makeUrl(url, args);
|
|
140
151
|
return (0, import_react_query.useQuery)(__spreadValues({
|
|
141
152
|
queryKey: [QUERY_KEY_PREFIX + model, url, args],
|
|
142
|
-
queryFn: () => fetcher(reqUrl, void 0,
|
|
153
|
+
queryFn: () => fetcher(reqUrl, void 0, fetch2, false)
|
|
143
154
|
}, options));
|
|
144
155
|
}
|
|
145
|
-
function infiniteQuery(model, url, args, options,
|
|
156
|
+
function infiniteQuery(model, url, args, options, fetch2) {
|
|
146
157
|
return (0, import_react_query.useInfiniteQuery)(__spreadValues({
|
|
147
158
|
queryKey: [QUERY_KEY_PREFIX + model, url, args],
|
|
148
159
|
queryFn: ({ pageParam }) => {
|
|
149
|
-
return fetcher(makeUrl(url, pageParam != null ? pageParam : args), void 0,
|
|
160
|
+
return fetcher(makeUrl(url, pageParam != null ? pageParam : args), void 0, fetch2, false);
|
|
150
161
|
}
|
|
151
162
|
}, options));
|
|
152
163
|
}
|
|
153
|
-
function postMutation(model, url, options,
|
|
164
|
+
function postMutation(model, url, options, fetch2, invalidateQueries = true, checkReadBack) {
|
|
154
165
|
const queryClient = (0, import_react_query.useQueryClient)();
|
|
155
166
|
const mutationFn = (data) => fetcher(
|
|
156
167
|
url,
|
|
@@ -161,14 +172,14 @@ function postMutation(model, url, options, fetch, invalidateQueries = true, chec
|
|
|
161
172
|
},
|
|
162
173
|
body: marshal(data)
|
|
163
174
|
},
|
|
164
|
-
|
|
175
|
+
fetch2,
|
|
165
176
|
checkReadBack
|
|
166
177
|
);
|
|
167
178
|
const finalOptions = mergeOptions(model, options, invalidateQueries, mutationFn, queryClient);
|
|
168
179
|
const mutation = (0, import_react_query.useMutation)(finalOptions);
|
|
169
180
|
return mutation;
|
|
170
181
|
}
|
|
171
|
-
function putMutation(model, url, options,
|
|
182
|
+
function putMutation(model, url, options, fetch2, invalidateQueries = true, checkReadBack) {
|
|
172
183
|
const queryClient = (0, import_react_query.useQueryClient)();
|
|
173
184
|
const mutationFn = (data) => fetcher(
|
|
174
185
|
url,
|
|
@@ -179,21 +190,21 @@ function putMutation(model, url, options, fetch, invalidateQueries = true, check
|
|
|
179
190
|
},
|
|
180
191
|
body: marshal(data)
|
|
181
192
|
},
|
|
182
|
-
|
|
193
|
+
fetch2,
|
|
183
194
|
checkReadBack
|
|
184
195
|
);
|
|
185
196
|
const finalOptions = mergeOptions(model, options, invalidateQueries, mutationFn, queryClient);
|
|
186
197
|
const mutation = (0, import_react_query.useMutation)(finalOptions);
|
|
187
198
|
return mutation;
|
|
188
199
|
}
|
|
189
|
-
function deleteMutation(model, url, options,
|
|
200
|
+
function deleteMutation(model, url, options, fetch2, invalidateQueries = true, checkReadBack) {
|
|
190
201
|
const queryClient = (0, import_react_query.useQueryClient)();
|
|
191
202
|
const mutationFn = (data) => fetcher(
|
|
192
203
|
makeUrl(url, data),
|
|
193
204
|
{
|
|
194
205
|
method: "DELETE"
|
|
195
206
|
},
|
|
196
|
-
|
|
207
|
+
fetch2,
|
|
197
208
|
checkReadBack
|
|
198
209
|
);
|
|
199
210
|
const finalOptions = mergeOptions(model, options, invalidateQueries, mutationFn, queryClient);
|
package/runtime/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/react.ts","../../src/runtime/common.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type MutateFunction,\n type QueryClient,\n type UseInfiniteQueryOptions,\n type UseMutationOptions,\n type UseQueryOptions,\n} from '@tanstack/react-query';\nimport { createContext } from 'react';\nimport {\n DEFAULT_QUERY_ENDPOINT,\n FetchFn,\n QUERY_KEY_PREFIX,\n fetcher,\n makeUrl,\n marshal,\n type APIContext,\n} from './common';\n\n/**\n * Context for configuring react hooks.\n */\nexport const RequestHandlerContext = createContext<APIContext>({\n endpoint: DEFAULT_QUERY_ENDPOINT,\n fetch: undefined,\n});\n\n/**\n * Context provider.\n */\nexport const Provider = RequestHandlerContext.Provider;\n\n/**\n * Creates a react-query query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query options object\n * @returns useQuery hook\n */\nexport function query<R>(model: string, url: string, args?: unknown, options?: UseQueryOptions<R>, fetch?: FetchFn) {\n const reqUrl = makeUrl(url, args);\n return useQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: () => fetcher<R, false>(reqUrl, undefined, fetch, false),\n ...options,\n });\n}\n\n/**\n * Creates a react-query infinite query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The initial request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query infinite query options object\n * @returns useInfiniteQuery hook\n */\nexport function infiniteQuery<R>(\n model: string,\n url: string,\n args?: unknown,\n options?: UseInfiniteQueryOptions<R>,\n fetch?: FetchFn\n) {\n return useInfiniteQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: ({ pageParam }) => {\n return fetcher<R, false>(makeUrl(url, pageParam ?? args), undefined, fetch, false);\n },\n ...options,\n });\n}\n\n/**\n * Creates a POST mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function postMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a PUT mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function putMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'PUT',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a DELETE mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function deleteMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n makeUrl(url, data),\n {\n method: 'DELETE',\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\nfunction mergeOptions<T, R = any>(\n model: string,\n options: Omit<UseMutationOptions<R, unknown, T, unknown>, 'mutationFn'> | undefined,\n invalidateQueries: boolean,\n mutationFn: MutateFunction<R, unknown, T>,\n queryClient: QueryClient\n): UseMutationOptions<R, unknown, T, unknown> {\n const result = { ...options, mutationFn };\n if (options?.onSuccess || invalidateQueries) {\n result.onSuccess = (...args) => {\n if (invalidateQueries) {\n queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]);\n }\n return options?.onSuccess?.(...args);\n };\n }\n return result;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { serialize, deserialize } from '@zenstackhq/runtime/browser';\n\n/**\n * The default query endpoint.\n */\nexport const DEFAULT_QUERY_ENDPOINT = '/api/model';\n\n/**\n * Prefix for react-query keys.\n */\nexport const QUERY_KEY_PREFIX = 'zenstack:';\n\n/**\n * Function signature for `fetch`.\n */\nexport type FetchFn = (url: string, options?: RequestInit) => Promise<Response>;\n\n/**\n * Context type for configuring the hooks.\n */\nexport type APIContext = {\n /**\n * The endpoint to use for the queries.\n */\n endpoint: string;\n\n /**\n * A custom fetch function for sending the HTTP requests.\n */\n fetch?: FetchFn;\n};\n\nexport async function fetcher<R, C extends boolean>(\n url: string,\n options?: RequestInit,\n fetch?: FetchFn,\n checkReadBack?: C\n): Promise<C extends true ? R | undefined : R> {\n const _fetch = fetch ?? window.fetch;\n const res = await _fetch(url, options);\n if (!res.ok) {\n const errData = unmarshal(await res.text());\n if (\n checkReadBack !== false &&\n errData.error?.prisma &&\n errData.error?.code === 'P2004' &&\n errData.error?.reason === 'RESULT_NOT_READABLE'\n ) {\n // policy doesn't allow mutation result to be read back, just return undefined\n return undefined as any;\n }\n const error: Error & { info?: unknown; status?: number } = new Error(\n 'An error occurred while fetching the data.'\n );\n error.info = errData.error;\n error.status = res.status;\n throw error;\n }\n\n const textResult = await res.text();\n try {\n return unmarshal(textResult).data as R;\n } catch (err) {\n console.error(`Unable to deserialize data:`, textResult);\n throw err;\n }\n}\n\nexport function marshal(value: unknown) {\n const { data, meta } = serialize(value);\n if (meta) {\n return JSON.stringify({ ...(data as any), meta: { serialization: meta } });\n } else {\n return JSON.stringify(data);\n }\n}\n\nexport function unmarshal(value: string) {\n const parsed = JSON.parse(value);\n if (parsed.data && parsed.meta?.serialization) {\n const deserializedData = deserialize(parsed.data, parsed.meta.serialization);\n return { ...parsed, data: deserializedData };\n } else {\n return parsed;\n }\n}\n\nexport function makeUrl(url: string, args: unknown) {\n if (!args) {\n return url;\n }\n\n const { data, meta } = serialize(args);\n let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;\n if (meta) {\n result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,yBAUO;AACP,mBAA8B;;;ACX9B,qBAAuC;AAKhC,IAAM,yBAAyB;AAK/B,IAAM,mBAAmB;AAsBhC,SAAsB,QAClB,KACA,SACA,OACA,eAC2C;AAAA;AAtC/C;AAuCI,UAAM,SAAS,wBAAS,OAAO;AAC/B,UAAM,MAAM,MAAM,OAAO,KAAK,OAAO;AACrC,QAAI,CAAC,IAAI,IAAI;AACT,YAAM,UAAU,UAAU,MAAM,IAAI,KAAK,CAAC;AAC1C,UACI,kBAAkB,WAClB,aAAQ,UAAR,mBAAe,aACf,aAAQ,UAAR,mBAAe,UAAS,aACxB,aAAQ,UAAR,mBAAe,YAAW,uBAC5B;AAEE,eAAO;AAAA,MACX;AACA,YAAM,QAAqD,IAAI;AAAA,QAC3D;AAAA,MACJ;AACA,YAAM,OAAO,QAAQ;AACrB,YAAM,SAAS,IAAI;AACnB,YAAM;AAAA,IACV;AAEA,UAAM,aAAa,MAAM,IAAI,KAAK;AAClC,QAAI;AACA,aAAO,UAAU,UAAU,EAAE;AAAA,IACjC,SAAS,KAAK;AACV,cAAQ,MAAM,+BAA+B,UAAU;AACvD,YAAM;AAAA,IACV;AAAA,EACJ;AAAA;AAEO,SAAS,QAAQ,OAAgB;AACpC,QAAM,EAAE,MAAM,KAAK,QAAI,0BAAU,KAAK;AACtC,MAAI,MAAM;AACN,WAAO,KAAK,UAAU,iCAAM,OAAN,EAAoB,MAAM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,UAAL,EAAc,WAAW;AACxC,OAAI,mCAAS,cAAa,mBAAmB;AACzC,WAAO,YAAY,IAAI,SAAS;AAnMxC;AAoMY,UAAI,mBAAmB;AACnB,oBAAY,kBAAkB,CAAC,mBAAmB,KAAK,CAAC;AAAA,MAC5D;AACA,cAAO,wCAAS,cAAT,iCAAqB,GAAG;AAAA,IACnC;AAAA,EACJ;AACA,SAAO;AACX;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/react.ts","../../src/runtime/common.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type MutateFunction,\n type QueryClient,\n type UseInfiniteQueryOptions,\n type UseMutationOptions,\n type UseQueryOptions,\n} from '@tanstack/react-query';\nimport { createContext } from 'react';\nimport {\n DEFAULT_QUERY_ENDPOINT,\n FetchFn,\n QUERY_KEY_PREFIX,\n fetcher,\n makeUrl,\n marshal,\n type APIContext,\n} from './common';\n\n/**\n * Context for configuring react hooks.\n */\nexport const RequestHandlerContext = createContext<APIContext>({\n endpoint: DEFAULT_QUERY_ENDPOINT,\n fetch: undefined,\n});\n\n/**\n * Context provider.\n */\nexport const Provider = RequestHandlerContext.Provider;\n\n/**\n * Creates a react-query query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query options object\n * @returns useQuery hook\n */\nexport function query<R>(model: string, url: string, args?: unknown, options?: UseQueryOptions<R>, fetch?: FetchFn) {\n const reqUrl = makeUrl(url, args);\n return useQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: () => fetcher<R, false>(reqUrl, undefined, fetch, false),\n ...options,\n });\n}\n\n/**\n * Creates a react-query infinite query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The initial request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query infinite query options object\n * @returns useInfiniteQuery hook\n */\nexport function infiniteQuery<R>(\n model: string,\n url: string,\n args?: unknown,\n options?: UseInfiniteQueryOptions<R>,\n fetch?: FetchFn\n) {\n return useInfiniteQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: ({ pageParam }) => {\n return fetcher<R, false>(makeUrl(url, pageParam ?? args), undefined, fetch, false);\n },\n ...options,\n });\n}\n\n/**\n * Creates a POST mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function postMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a PUT mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function putMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'PUT',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a DELETE mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function deleteMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n makeUrl(url, data),\n {\n method: 'DELETE',\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\nfunction mergeOptions<T, R = any>(\n model: string,\n options: Omit<UseMutationOptions<R, unknown, T, unknown>, 'mutationFn'> | undefined,\n invalidateQueries: boolean,\n mutationFn: MutateFunction<R, unknown, T>,\n queryClient: QueryClient\n): UseMutationOptions<R, unknown, T, unknown> {\n const result = { ...options, mutationFn };\n if (options?.onSuccess || invalidateQueries) {\n result.onSuccess = (...args) => {\n if (invalidateQueries) {\n queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]);\n }\n return options?.onSuccess?.(...args);\n };\n }\n return result;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { deserialize, serialize } from '@zenstackhq/runtime/browser';\nimport * as crossFetch from 'cross-fetch';\n\n/**\n * The default query endpoint.\n */\nexport const DEFAULT_QUERY_ENDPOINT = '/api/model';\n\n/**\n * Prefix for react-query keys.\n */\nexport const QUERY_KEY_PREFIX = 'zenstack:';\n\n/**\n * Function signature for `fetch`.\n */\nexport type FetchFn = (url: string, options?: RequestInit) => Promise<Response>;\n\n/**\n * Context type for configuring the hooks.\n */\nexport type APIContext = {\n /**\n * The endpoint to use for the queries.\n */\n endpoint?: string;\n\n /**\n * A custom fetch function for sending the HTTP requests.\n */\n fetch?: FetchFn;\n};\n\nexport async function fetcher<R, C extends boolean>(\n url: string,\n options?: RequestInit,\n fetch?: FetchFn,\n checkReadBack?: C\n): Promise<C extends true ? R | undefined : R> {\n const _fetch = fetch ?? crossFetch.fetch;\n const res = await _fetch(url, options);\n if (!res.ok) {\n const errData = unmarshal(await res.text());\n if (\n checkReadBack !== false &&\n errData.error?.prisma &&\n errData.error?.code === 'P2004' &&\n errData.error?.reason === 'RESULT_NOT_READABLE'\n ) {\n // policy doesn't allow mutation result to be read back, just return undefined\n return undefined as any;\n }\n const error: Error & { info?: unknown; status?: number } = new Error(\n 'An error occurred while fetching the data.'\n );\n error.info = errData.error;\n error.status = res.status;\n throw error;\n }\n\n const textResult = await res.text();\n try {\n return unmarshal(textResult).data as R;\n } catch (err) {\n console.error(`Unable to deserialize data:`, textResult);\n throw err;\n }\n}\n\nexport function marshal(value: unknown) {\n const { data, meta } = serialize(value);\n if (meta) {\n return JSON.stringify({ ...(data as any), meta: { serialization: meta } });\n } else {\n return JSON.stringify(data);\n }\n}\n\nexport function unmarshal(value: string) {\n const parsed = JSON.parse(value);\n if (parsed.data && parsed.meta?.serialization) {\n const deserializedData = deserialize(parsed.data, parsed.meta.serialization);\n return { ...parsed, data: deserializedData };\n } else {\n return parsed;\n }\n}\n\nexport function makeUrl(url: string, args: unknown) {\n if (!args) {\n return url;\n }\n\n const { data, meta } = serialize(args);\n let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;\n if (meta) {\n result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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 +48,14 @@ import {
|
|
|
48
48
|
import { createContext } from "react";
|
|
49
49
|
|
|
50
50
|
// src/runtime/common.ts
|
|
51
|
-
import {
|
|
51
|
+
import { deserialize, serialize } from "@zenstackhq/runtime/browser";
|
|
52
|
+
import * as crossFetch from "cross-fetch";
|
|
52
53
|
var DEFAULT_QUERY_ENDPOINT = "/api/model";
|
|
53
54
|
var QUERY_KEY_PREFIX = "zenstack:";
|
|
54
|
-
function fetcher(url, options,
|
|
55
|
+
function fetcher(url, options, fetch2, checkReadBack) {
|
|
55
56
|
return __async(this, null, function* () {
|
|
56
57
|
var _a, _b, _c;
|
|
57
|
-
const _fetch =
|
|
58
|
+
const _fetch = fetch2 != null ? fetch2 : crossFetch.fetch;
|
|
58
59
|
const res = yield _fetch(url, options);
|
|
59
60
|
if (!res.ok) {
|
|
60
61
|
const errData = unmarshal(yield res.text());
|
|
@@ -113,22 +114,22 @@ var RequestHandlerContext = createContext({
|
|
|
113
114
|
fetch: void 0
|
|
114
115
|
});
|
|
115
116
|
var Provider = RequestHandlerContext.Provider;
|
|
116
|
-
function query(model, url, args, options,
|
|
117
|
+
function query(model, url, args, options, fetch2) {
|
|
117
118
|
const reqUrl = makeUrl(url, args);
|
|
118
119
|
return useQuery(__spreadValues({
|
|
119
120
|
queryKey: [QUERY_KEY_PREFIX + model, url, args],
|
|
120
|
-
queryFn: () => fetcher(reqUrl, void 0,
|
|
121
|
+
queryFn: () => fetcher(reqUrl, void 0, fetch2, false)
|
|
121
122
|
}, options));
|
|
122
123
|
}
|
|
123
|
-
function infiniteQuery(model, url, args, options,
|
|
124
|
+
function infiniteQuery(model, url, args, options, fetch2) {
|
|
124
125
|
return useInfiniteQuery(__spreadValues({
|
|
125
126
|
queryKey: [QUERY_KEY_PREFIX + model, url, args],
|
|
126
127
|
queryFn: ({ pageParam }) => {
|
|
127
|
-
return fetcher(makeUrl(url, pageParam != null ? pageParam : args), void 0,
|
|
128
|
+
return fetcher(makeUrl(url, pageParam != null ? pageParam : args), void 0, fetch2, false);
|
|
128
129
|
}
|
|
129
130
|
}, options));
|
|
130
131
|
}
|
|
131
|
-
function postMutation(model, url, options,
|
|
132
|
+
function postMutation(model, url, options, fetch2, invalidateQueries = true, checkReadBack) {
|
|
132
133
|
const queryClient = useQueryClient();
|
|
133
134
|
const mutationFn = (data) => fetcher(
|
|
134
135
|
url,
|
|
@@ -139,14 +140,14 @@ function postMutation(model, url, options, fetch, invalidateQueries = true, chec
|
|
|
139
140
|
},
|
|
140
141
|
body: marshal(data)
|
|
141
142
|
},
|
|
142
|
-
|
|
143
|
+
fetch2,
|
|
143
144
|
checkReadBack
|
|
144
145
|
);
|
|
145
146
|
const finalOptions = mergeOptions(model, options, invalidateQueries, mutationFn, queryClient);
|
|
146
147
|
const mutation = useMutation(finalOptions);
|
|
147
148
|
return mutation;
|
|
148
149
|
}
|
|
149
|
-
function putMutation(model, url, options,
|
|
150
|
+
function putMutation(model, url, options, fetch2, invalidateQueries = true, checkReadBack) {
|
|
150
151
|
const queryClient = useQueryClient();
|
|
151
152
|
const mutationFn = (data) => fetcher(
|
|
152
153
|
url,
|
|
@@ -157,21 +158,21 @@ function putMutation(model, url, options, fetch, invalidateQueries = true, check
|
|
|
157
158
|
},
|
|
158
159
|
body: marshal(data)
|
|
159
160
|
},
|
|
160
|
-
|
|
161
|
+
fetch2,
|
|
161
162
|
checkReadBack
|
|
162
163
|
);
|
|
163
164
|
const finalOptions = mergeOptions(model, options, invalidateQueries, mutationFn, queryClient);
|
|
164
165
|
const mutation = useMutation(finalOptions);
|
|
165
166
|
return mutation;
|
|
166
167
|
}
|
|
167
|
-
function deleteMutation(model, url, options,
|
|
168
|
+
function deleteMutation(model, url, options, fetch2, invalidateQueries = true, checkReadBack) {
|
|
168
169
|
const queryClient = useQueryClient();
|
|
169
170
|
const mutationFn = (data) => fetcher(
|
|
170
171
|
makeUrl(url, data),
|
|
171
172
|
{
|
|
172
173
|
method: "DELETE"
|
|
173
174
|
},
|
|
174
|
-
|
|
175
|
+
fetch2,
|
|
175
176
|
checkReadBack
|
|
176
177
|
);
|
|
177
178
|
const finalOptions = mergeOptions(model, options, invalidateQueries, mutationFn, queryClient);
|
package/runtime/react.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/react.ts","../../src/runtime/common.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type MutateFunction,\n type QueryClient,\n type UseInfiniteQueryOptions,\n type UseMutationOptions,\n type UseQueryOptions,\n} from '@tanstack/react-query';\nimport { createContext } from 'react';\nimport {\n DEFAULT_QUERY_ENDPOINT,\n FetchFn,\n QUERY_KEY_PREFIX,\n fetcher,\n makeUrl,\n marshal,\n type APIContext,\n} from './common';\n\n/**\n * Context for configuring react hooks.\n */\nexport const RequestHandlerContext = createContext<APIContext>({\n endpoint: DEFAULT_QUERY_ENDPOINT,\n fetch: undefined,\n});\n\n/**\n * Context provider.\n */\nexport const Provider = RequestHandlerContext.Provider;\n\n/**\n * Creates a react-query query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query options object\n * @returns useQuery hook\n */\nexport function query<R>(model: string, url: string, args?: unknown, options?: UseQueryOptions<R>, fetch?: FetchFn) {\n const reqUrl = makeUrl(url, args);\n return useQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: () => fetcher<R, false>(reqUrl, undefined, fetch, false),\n ...options,\n });\n}\n\n/**\n * Creates a react-query infinite query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The initial request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query infinite query options object\n * @returns useInfiniteQuery hook\n */\nexport function infiniteQuery<R>(\n model: string,\n url: string,\n args?: unknown,\n options?: UseInfiniteQueryOptions<R>,\n fetch?: FetchFn\n) {\n return useInfiniteQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: ({ pageParam }) => {\n return fetcher<R, false>(makeUrl(url, pageParam ?? args), undefined, fetch, false);\n },\n ...options,\n });\n}\n\n/**\n * Creates a POST mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function postMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a PUT mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function putMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'PUT',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a DELETE mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function deleteMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n makeUrl(url, data),\n {\n method: 'DELETE',\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\nfunction mergeOptions<T, R = any>(\n model: string,\n options: Omit<UseMutationOptions<R, unknown, T, unknown>, 'mutationFn'> | undefined,\n invalidateQueries: boolean,\n mutationFn: MutateFunction<R, unknown, T>,\n queryClient: QueryClient\n): UseMutationOptions<R, unknown, T, unknown> {\n const result = { ...options, mutationFn };\n if (options?.onSuccess || invalidateQueries) {\n result.onSuccess = (...args) => {\n if (invalidateQueries) {\n queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]);\n }\n return options?.onSuccess?.(...args);\n };\n }\n return result;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { serialize, deserialize } from '@zenstackhq/runtime/browser';\n\n/**\n * The default query endpoint.\n */\nexport const DEFAULT_QUERY_ENDPOINT = '/api/model';\n\n/**\n * Prefix for react-query keys.\n */\nexport const QUERY_KEY_PREFIX = 'zenstack:';\n\n/**\n * Function signature for `fetch`.\n */\nexport type FetchFn = (url: string, options?: RequestInit) => Promise<Response>;\n\n/**\n * Context type for configuring the hooks.\n */\nexport type APIContext = {\n /**\n * The endpoint to use for the queries.\n */\n endpoint: string;\n\n /**\n * A custom fetch function for sending the HTTP requests.\n */\n fetch?: FetchFn;\n};\n\nexport async function fetcher<R, C extends boolean>(\n url: string,\n options?: RequestInit,\n fetch?: FetchFn,\n checkReadBack?: C\n): Promise<C extends true ? R | undefined : R> {\n const _fetch = fetch ?? window.fetch;\n const res = await _fetch(url, options);\n if (!res.ok) {\n const errData = unmarshal(await res.text());\n if (\n checkReadBack !== false &&\n errData.error?.prisma &&\n errData.error?.code === 'P2004' &&\n errData.error?.reason === 'RESULT_NOT_READABLE'\n ) {\n // policy doesn't allow mutation result to be read back, just return undefined\n return undefined as any;\n }\n const error: Error & { info?: unknown; status?: number } = new Error(\n 'An error occurred while fetching the data.'\n );\n error.info = errData.error;\n error.status = res.status;\n throw error;\n }\n\n const textResult = await res.text();\n try {\n return unmarshal(textResult).data as R;\n } catch (err) {\n console.error(`Unable to deserialize data:`, textResult);\n throw err;\n }\n}\n\nexport function marshal(value: unknown) {\n const { data, meta } = serialize(value);\n if (meta) {\n return JSON.stringify({ ...(data as any), meta: { serialization: meta } });\n } else {\n return JSON.stringify(data);\n }\n}\n\nexport function unmarshal(value: string) {\n const parsed = JSON.parse(value);\n if (parsed.data && parsed.meta?.serialization) {\n const deserializedData = deserialize(parsed.data, parsed.meta.serialization);\n return { ...parsed, data: deserializedData };\n } else {\n return parsed;\n }\n}\n\nexport function makeUrl(url: string, args: unknown) {\n if (!args) {\n return url;\n }\n\n const { data, meta } = serialize(args);\n let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;\n if (meta) {\n result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMG;AACP,SAAS,qBAAqB;;;ACX9B,SAAS,WAAW,mBAAmB;AAKhC,IAAM,yBAAyB;AAK/B,IAAM,mBAAmB;AAsBhC,SAAsB,QAClB,KACA,SACA,OACA,eAC2C;AAAA;AAtC/C;AAuCI,UA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Ac,eAAe;AACnC,QAAM,aAAa,CAAC,SAChB;AAAA,IACI;AAAA,IACA;AAAA,MACI,QAAQ;AAAA,MACR,SAAS;AAAA,QACL,gBAAgB;AAAA,MACpB;AAAA,MACA,MAAM,QAAQ,IAAI;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AAEJ,QAAM,eAAe,aAAwB,OAAO,SAAS,mBAAmB,YAAY,WAAW;AACvG,QAAM,WAAW,YAAgC,YAAY;AAC7D,SAAO;AACX;AAWO,SAAS,eACZ,OACA,KACA,SACA,OACA,oBAAoB,MACpB,eACF;AACE,QAAM,cAAc,eAAe;AACnC,QAAM,aAAa,CAAC,SAChB;AAAA,IACI,QAAQ,KAAK,IAAI;AAAA,IACjB;AAAA,MACI,QAAQ;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AAEJ,QAAM,eAAe,aAAwB,OAAO,SAAS,mBAAmB,YAAY,WAAW;AACvG,QAAM,WAAW,YAAgC,YAAY;AAC7D,SAAO;AACX;AAEA,SAAS,aACL,OACA,SACA,mBACA,YACA,aAC0C;AAC1C,QAAM,SAAS,iCAAK,UAAL,EAAc,WAAW;AACxC,OAAI,mCAAS,cAAa,mBAAmB;AACzC,WAAO,YAAY,IAAI,SAAS;AAnMxC;AAoMY,UAAI,mBAAmB;AACnB,oBAAY,kBAAkB,CAAC,mBAAmB,KAAK,CAAC;AAAA,MAC5D;AACA,cAAO,wCAAS,cAAT,iCAAqB,GAAG;AAAA,IACnC;AAAA,EACJ;AACA,SAAO;AACX;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/react.ts","../../src/runtime/common.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type MutateFunction,\n type QueryClient,\n type UseInfiniteQueryOptions,\n type UseMutationOptions,\n type UseQueryOptions,\n} from '@tanstack/react-query';\nimport { createContext } from 'react';\nimport {\n DEFAULT_QUERY_ENDPOINT,\n FetchFn,\n QUERY_KEY_PREFIX,\n fetcher,\n makeUrl,\n marshal,\n type APIContext,\n} from './common';\n\n/**\n * Context for configuring react hooks.\n */\nexport const RequestHandlerContext = createContext<APIContext>({\n endpoint: DEFAULT_QUERY_ENDPOINT,\n fetch: undefined,\n});\n\n/**\n * Context provider.\n */\nexport const Provider = RequestHandlerContext.Provider;\n\n/**\n * Creates a react-query query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query options object\n * @returns useQuery hook\n */\nexport function query<R>(model: string, url: string, args?: unknown, options?: UseQueryOptions<R>, fetch?: FetchFn) {\n const reqUrl = makeUrl(url, args);\n return useQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: () => fetcher<R, false>(reqUrl, undefined, fetch, false),\n ...options,\n });\n}\n\n/**\n * Creates a react-query infinite query.\n *\n * @param model The name of the model under query.\n * @param url The request URL.\n * @param args The initial request args object, URL-encoded and appended as \"?q=\" parameter\n * @param options The react-query infinite query options object\n * @returns useInfiniteQuery hook\n */\nexport function infiniteQuery<R>(\n model: string,\n url: string,\n args?: unknown,\n options?: UseInfiniteQueryOptions<R>,\n fetch?: FetchFn\n) {\n return useInfiniteQuery<R>({\n queryKey: [QUERY_KEY_PREFIX + model, url, args],\n queryFn: ({ pageParam }) => {\n return fetcher<R, false>(makeUrl(url, pageParam ?? args), undefined, fetch, false);\n },\n ...options,\n });\n}\n\n/**\n * Creates a POST mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function postMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a PUT mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function putMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n url,\n {\n method: 'PUT',\n headers: {\n 'content-type': 'application/json',\n },\n body: marshal(data),\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\n/**\n * Creates a DELETE mutation with react-query.\n *\n * @param model The name of the model under mutation.\n * @param url The request URL.\n * @param options The react-query options.\n * @param invalidateQueries Whether to invalidate queries after mutation.\n * @returns useMutation hooks\n */\nexport function deleteMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(\n model: string,\n url: string,\n options?: Omit<UseMutationOptions<Result, unknown, T>, 'mutationFn'>,\n fetch?: FetchFn,\n invalidateQueries = true,\n checkReadBack?: C\n) {\n const queryClient = useQueryClient();\n const mutationFn = (data: any) =>\n fetcher<R, C>(\n makeUrl(url, data),\n {\n method: 'DELETE',\n },\n fetch,\n checkReadBack\n ) as Promise<Result>;\n\n const finalOptions = mergeOptions<T, Result>(model, options, invalidateQueries, mutationFn, queryClient);\n const mutation = useMutation<Result, unknown, T>(finalOptions);\n return mutation;\n}\n\nfunction mergeOptions<T, R = any>(\n model: string,\n options: Omit<UseMutationOptions<R, unknown, T, unknown>, 'mutationFn'> | undefined,\n invalidateQueries: boolean,\n mutationFn: MutateFunction<R, unknown, T>,\n queryClient: QueryClient\n): UseMutationOptions<R, unknown, T, unknown> {\n const result = { ...options, mutationFn };\n if (options?.onSuccess || invalidateQueries) {\n result.onSuccess = (...args) => {\n if (invalidateQueries) {\n queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]);\n }\n return options?.onSuccess?.(...args);\n };\n }\n return result;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { deserialize, serialize } from '@zenstackhq/runtime/browser';\nimport * as crossFetch from 'cross-fetch';\n\n/**\n * The default query endpoint.\n */\nexport const DEFAULT_QUERY_ENDPOINT = '/api/model';\n\n/**\n * Prefix for react-query keys.\n */\nexport const QUERY_KEY_PREFIX = 'zenstack:';\n\n/**\n * Function signature for `fetch`.\n */\nexport type FetchFn = (url: string, options?: RequestInit) => Promise<Response>;\n\n/**\n * Context type for configuring the hooks.\n */\nexport type APIContext = {\n /**\n * The endpoint to use for the queries.\n */\n endpoint?: string;\n\n /**\n * A custom fetch function for sending the HTTP requests.\n */\n fetch?: FetchFn;\n};\n\nexport async function fetcher<R, C extends boolean>(\n url: string,\n options?: RequestInit,\n fetch?: FetchFn,\n checkReadBack?: C\n): Promise<C extends true ? R | undefined : R> {\n const _fetch = fetch ?? crossFetch.fetch;\n const res = await _fetch(url, options);\n if (!res.ok) {\n const errData = unmarshal(await res.text());\n if (\n checkReadBack !== false &&\n errData.error?.prisma &&\n errData.error?.code === 'P2004' &&\n errData.error?.reason === 'RESULT_NOT_READABLE'\n ) {\n // policy doesn't allow mutation result to be read back, just return undefined\n return undefined as any;\n }\n const error: Error & { info?: unknown; status?: number } = new Error(\n 'An error occurred while fetching the data.'\n );\n error.info = errData.error;\n error.status = res.status;\n throw error;\n }\n\n const textResult = await res.text();\n try {\n return unmarshal(textResult).data as R;\n } catch (err) {\n console.error(`Unable to deserialize data:`, textResult);\n throw err;\n }\n}\n\nexport function marshal(value: unknown) {\n const { data, meta } = serialize(value);\n if (meta) {\n return JSON.stringify({ ...(data as any), meta: { serialization: meta } });\n } else {\n return JSON.stringify(data);\n }\n}\n\nexport function unmarshal(value: string) {\n const parsed = JSON.parse(value);\n if (parsed.data && parsed.meta?.serialization) {\n const deserializedData = deserialize(parsed.data, parsed.meta.serialization);\n return { ...parsed, data: deserializedData };\n } else {\n return parsed;\n }\n}\n\nexport function makeUrl(url: string, args: unknown) {\n if (!args) {\n return url;\n }\n\n const { data, meta } = serialize(args);\n let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;\n if (meta) {\n result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMG;AACP,SAAS,qBAAqB;;;ACX9B,SAAS,aAAa,iBAAiB;AACvC,YAAY,gBAAgB;AAKrB,IAAM,yBAAyB;AAK/B,IAAM,mBAAmB;AAsBhC,SAAsB,QAClB,KACA,SACAA,QACA,eAC2C;AAAA;AAvC/C;AAwCI,UAAM,SAASA,UAAA,OAAAA,SAAoB;AACnC,UAAM,MAAM,MAAM,OAAO,KAAK,OAAO;AACrC,QAAI,CAAC,IAAI,IAAI;AACT,YAAM,UAAU,UAAU,MAAM,IAAI,KAAK,CAAC;AAC1C,UACI,kBAAkB,WAClB,aAAQ,UAAR,mBAAe,aACf,aAAQ,UAAR,mBAAe,UAAS,aACxB,aAAQ,UAAR,mBAAe,YAAW,uBAC5B;AAEE,eAAO;AAAA,MACX;AACA,YAAM,QAAqD,IAAI;AAAA,QAC3D;AAAA,MACJ;AACA,YAAM,OAAO,QAAQ;A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oBAAoB,MACpB,eACF;AACE,QAAM,cAAc,eAAe;AACnC,QAAM,aAAa,CAAC,SAChB;AAAA,IACI,QAAQ,KAAK,IAAI;AAAA,IACjB;AAAA,MACI,QAAQ;AAAA,IACZ;AAAA,IACAA;AAAA,IACA;AAAA,EACJ;AAEJ,QAAM,eAAe,aAAwB,OAAO,SAAS,mBAAmB,YAAY,WAAW;AACvG,QAAM,WAAW,YAAgC,YAAY;AAC7D,SAAO;AACX;AAEA,SAAS,aACL,OACA,SACA,mBACA,YACA,aAC0C;AAC1C,QAAM,SAAS,iCAAK,UAAL,EAAc,WAAW;AACxC,OAAI,mCAAS,cAAa,mBAAmB;AACzC,WAAO,YAAY,IAAI,SAAS;AAnMxC;AAoMY,UAAI,mBAAmB;AACnB,oBAAY,kBAAkB,CAAC,mBAAmB,KAAK,CAAC;AAAA,MAC5D;AACA,cAAO,wCAAS,cAAT,iCAAqB,GAAG;AAAA,IACnC;AAAA,EACJ;AACA,SAAO;AACX;","names":["fetch","fetch"]}
|
package/runtime/svelte.d.mts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import * as _tanstack_svelte_query from '@tanstack/svelte-query';
|
|
2
2
|
import { QueryOptions, CreateInfiniteQueryOptions, MutationOptions } from '@tanstack/svelte-query';
|
|
3
|
-
import { F as FetchFn } from './common-
|
|
4
|
-
export { A as RequestHandlerContext } from './common-52ab2c3a.js';
|
|
3
|
+
import { A as APIContext, F as FetchFn } from './common-83308e88.js';
|
|
5
4
|
|
|
6
5
|
/**
|
|
7
6
|
* Key for setting and getting the global query context.
|
|
8
7
|
*/
|
|
9
8
|
declare const SvelteQueryContextKey = "zenstack-svelte-query-context";
|
|
9
|
+
/**
|
|
10
|
+
* Set context for the generated TanStack Query hooks.
|
|
11
|
+
*/
|
|
12
|
+
declare function setHooksContext(context: APIContext): void;
|
|
10
13
|
/**
|
|
11
14
|
* Creates a svelte-query query.
|
|
12
15
|
*
|
|
@@ -58,4 +61,4 @@ declare function putMutation<T, R = any, C extends boolean = boolean, Result = C
|
|
|
58
61
|
*/
|
|
59
62
|
declare function deleteMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(model: string, url: string, options?: Omit<MutationOptions<Result, unknown, T>, 'mutationFn'>, fetch?: FetchFn, invalidateQueries?: boolean, checkReadBack?: C): _tanstack_svelte_query.CreateMutationResult<Result, unknown, T, unknown>;
|
|
60
63
|
|
|
61
|
-
export { SvelteQueryContextKey, deleteMutation, infiniteQuery, postMutation, putMutation, query };
|
|
64
|
+
export { APIContext as RequestHandlerContext, SvelteQueryContextKey, deleteMutation, infiniteQuery, postMutation, putMutation, query, setHooksContext };
|
package/runtime/svelte.d.ts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import * as _tanstack_svelte_query from '@tanstack/svelte-query';
|
|
2
2
|
import { QueryOptions, CreateInfiniteQueryOptions, MutationOptions } from '@tanstack/svelte-query';
|
|
3
|
-
import { F as FetchFn } from './common-
|
|
4
|
-
export { A as RequestHandlerContext } from './common-52ab2c3a.js';
|
|
3
|
+
import { A as APIContext, F as FetchFn } from './common-83308e88.js';
|
|
5
4
|
|
|
6
5
|
/**
|
|
7
6
|
* Key for setting and getting the global query context.
|
|
8
7
|
*/
|
|
9
8
|
declare const SvelteQueryContextKey = "zenstack-svelte-query-context";
|
|
9
|
+
/**
|
|
10
|
+
* Set context for the generated TanStack Query hooks.
|
|
11
|
+
*/
|
|
12
|
+
declare function setHooksContext(context: APIContext): void;
|
|
10
13
|
/**
|
|
11
14
|
* Creates a svelte-query query.
|
|
12
15
|
*
|
|
@@ -58,4 +61,4 @@ declare function putMutation<T, R = any, C extends boolean = boolean, Result = C
|
|
|
58
61
|
*/
|
|
59
62
|
declare function deleteMutation<T, R = any, C extends boolean = boolean, Result = C extends true ? R | undefined : R>(model: string, url: string, options?: Omit<MutationOptions<Result, unknown, T>, 'mutationFn'>, fetch?: FetchFn, invalidateQueries?: boolean, checkReadBack?: C): _tanstack_svelte_query.CreateMutationResult<Result, unknown, T, unknown>;
|
|
60
63
|
|
|
61
|
-
export { SvelteQueryContextKey, deleteMutation, infiniteQuery, postMutation, putMutation, query };
|
|
64
|
+
export { APIContext as RequestHandlerContext, SvelteQueryContextKey, deleteMutation, infiniteQuery, postMutation, putMutation, query, setHooksContext };
|