-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathquery.js
More file actions
351 lines (307 loc) · 10.7 KB
/
query.js
File metadata and controls
351 lines (307 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/** @import { RemoteQuery, RemoteQueryFunction } from '@sveltejs/kit' */
/** @import { RemoteInfo, MaybePromise } from 'types' */
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
import { get_request_store } from '@sveltejs/kit/internal/server';
import { create_remote_key, stringify_remote_arg } from '../../../shared.js';
import { prerendering } from '__sveltekit/environment';
import { create_validator, get_cache, get_response, run_remote_function } from './shared.js';
import { handle_error_and_jsonify } from '../../../server/utils.js';
import { HttpError, SvelteKitError } from '@sveltejs/kit/internal';
import { lazy_promise } from '../../../../utils/promise.js';
/**
* Creates a remote query. When called from the browser, the function will be invoked on the server via a `fetch` call.
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query) for full documentation.
*
* @template Output
* @overload
* @param {() => MaybePromise<Output>} fn
* @returns {RemoteQueryFunction<void, Output>}
* @since 2.27
*/
/**
* Creates a remote query. When called from the browser, the function will be invoked on the server via a `fetch` call.
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query) for full documentation.
*
* @template Input
* @template Output
* @overload
* @param {'unchecked'} validate
* @param {(arg: Input) => MaybePromise<Output>} fn
* @returns {RemoteQueryFunction<Input, Output>}
* @since 2.27
*/
/**
* Creates a remote query. When called from the browser, the function will be invoked on the server via a `fetch` call.
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query) for full documentation.
*
* @template {StandardSchemaV1} Schema
* @template Output
* @overload
* @param {Schema} schema
* @param {(arg: StandardSchemaV1.InferOutput<Schema>) => MaybePromise<Output>} fn
* @returns {RemoteQueryFunction<StandardSchemaV1.InferInput<Schema>, Output>}
* @since 2.27
*/
/**
* @template Input
* @template Output
* @param {any} validate_or_fn
* @param {(args?: Input) => MaybePromise<Output>} [maybe_fn]
* @returns {RemoteQueryFunction<Input, Output>}
* @since 2.27
*/
/*@__NO_SIDE_EFFECTS__*/
export function query(validate_or_fn, maybe_fn) {
/** @type {(arg?: Input) => Output} */
const fn = maybe_fn ?? validate_or_fn;
/** @type {(arg?: any) => MaybePromise<Input>} */
const validate = create_validator(validate_or_fn, maybe_fn);
/** @type {RemoteInfo} */
const __ = { type: 'query', id: '', name: '' };
/** @type {RemoteQueryFunction<Input, Output> & { __: RemoteInfo }} */
const wrapper = (arg) => {
if (prerendering) {
throw new Error(
`Cannot call query '${__.name}' while prerendering, as prerendered pages need static data. Use 'prerender' from $app/server instead`
);
}
const { event, state } = get_request_store();
const get_remote_function_result = () =>
run_remote_function(event, state, false, () => validate(arg), fn);
return create_query_resource({
__,
arg,
state,
start: () => get_response(__, arg, state, get_remote_function_result),
refresh: () => get_remote_function_result()
});
};
Object.defineProperty(wrapper, '__', { value: __ });
return wrapper;
}
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.
*
* @template Input
* @template Output
* @overload
* @param {'unchecked'} validate
* @param {(args: Input[]) => MaybePromise<(arg: Input, idx: number) => Output>} fn
* @returns {RemoteQueryFunction<Input, Output>}
* @since 2.35
*/
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.
*
* @template {StandardSchemaV1} Schema
* @template Output
* @overload
* @param {Schema} schema
* @param {(args: StandardSchemaV1.InferOutput<Schema>[]) => MaybePromise<(arg: StandardSchemaV1.InferOutput<Schema>, idx: number) => Output>} fn
* @returns {RemoteQueryFunction<StandardSchemaV1.InferInput<Schema>, Output>}
* @since 2.35
*/
/**
* @template Input
* @template Output
* @param {any} validate_or_fn
* @param {(args?: Input[]) => MaybePromise<(arg: Input, idx: number) => Output>} [maybe_fn]
* @returns {RemoteQueryFunction<Input, Output>}
* @since 2.35
*/
/*@__NO_SIDE_EFFECTS__*/
function batch(validate_or_fn, maybe_fn) {
/** @type {(args?: Input[]) => MaybePromise<(arg: Input, idx: number) => Output>} */
const fn = maybe_fn ?? validate_or_fn;
/** @type {(arg?: any) => MaybePromise<Input>} */
const validate = create_validator(validate_or_fn, maybe_fn);
/** @type {RemoteInfo & { type: 'query_batch' }} */
const __ = {
type: 'query_batch',
id: '',
name: '',
run: async (args, options) => {
const { event, state } = get_request_store();
return run_remote_function(
event,
state,
false,
async () => Promise.all(args.map(validate)),
async (/** @type {any[]} */ input) => {
const get_result = await fn(input);
return Promise.all(
input.map(async (arg, i) => {
try {
return { type: 'result', data: get_result(arg, i) };
} catch (error) {
return {
type: 'error',
error: await handle_error_and_jsonify(event, state, options, error),
status:
error instanceof HttpError || error instanceof SvelteKitError
? error.status
: 500
};
}
})
);
}
);
}
};
/** @type {{ args: any[], resolvers: Array<{resolve: (value: any) => void, reject: (error: any) => void}> }} */
let batching = { args: [], resolvers: [] };
/** @type {RemoteQueryFunction<Input, Output> & { __: RemoteInfo }} */
const wrapper = (arg) => {
if (prerendering) {
throw new Error(
`Cannot call query.batch '${__.name}' while prerendering, as prerendered pages need static data. Use 'prerender' from $app/server instead`
);
}
const { event, state } = get_request_store();
const get_remote_function_result = () => {
// Collect all the calls to the same query in the same macrotask,
// then execute them as one backend request.
return new Promise((resolve, reject) => {
// We don't need to deduplicate args here, because get_response already caches/reuses identical calls
batching.args.push(arg);
batching.resolvers.push({ resolve, reject });
if (batching.args.length > 1) return;
setTimeout(async () => {
const batched = batching;
batching = { args: [], resolvers: [] };
try {
return await run_remote_function(
event,
state,
false,
async () => Promise.all(batched.args.map(validate)),
async (input) => {
const get_result = await fn(input);
for (let i = 0; i < batched.resolvers.length; i++) {
try {
batched.resolvers[i].resolve(get_result(input[i], i));
} catch (error) {
batched.resolvers[i].reject(error);
}
}
}
);
} catch (error) {
for (const resolver of batched.resolvers) {
resolver.reject(error);
}
}
}, 0);
});
};
return create_query_resource({
__,
arg,
state,
start: () => get_response(__, arg, state, get_remote_function_result),
refresh: () => get_remote_function_result()
});
};
Object.defineProperty(wrapper, '__', { value: __ });
return wrapper;
}
const safe_query_keys = new Set(['run', 'set', 'refresh', '__']);
/**
* @param {object} options
* @param {RemoteInfo} options.__
* @param {any} options.arg
* @param {any} options.state
* @param {() => Promise<any>} options.start
* @param {() => Promise<any>} options.refresh
* @returns {RemoteQuery<any>}
*/
function create_query_resource({ __, arg, state, start, refresh }) {
const promise = lazy_promise(safe_query_keys, start);
return /** @type {RemoteQuery<any>} */ (
new Proxy(promise, {
get(target, property, receiver) {
if (state.is_in_universal_load && property !== 'run') {
throw new Error(
// TODO docs
'This query was called in a universal `load` function and is limited to calling `.run`.'
);
}
if (property === 'run') {
return () => promise;
}
if (property === 'set') {
/** @param {any} value */
return (value) => update_refresh_value(get_refresh_context(__, 'set', arg), value);
}
if (property === 'refresh') {
return () => {
const refresh_context = get_refresh_context(__, 'refresh', arg);
const is_immediate_refresh = !refresh_context.cache[refresh_context.cache_key];
const value = is_immediate_refresh ? promise : refresh();
return update_refresh_value(refresh_context, value, is_immediate_refresh);
};
}
if (property === 'withOverride') {
return () => {
throw new Error(`Cannot call '${__.name}.withOverride()' on the server`);
};
}
const value = Reflect.get(target, property, receiver);
if (typeof value === 'function') {
return value.bind(target);
}
return value;
}
})
);
}
// Add batch as a property to the query function
Object.defineProperty(query, 'batch', { value: batch, enumerable: true });
/**
* @param {RemoteInfo} __
* @param {'set' | 'refresh'} action
* @param {any} [arg]
* @returns {{ __: RemoteInfo; state: any; refreshes: Record<string, Promise<any>>; cache: Record<string, { serialize: boolean; data: any }>; refreshes_key: string; cache_key: string }}
*/
function get_refresh_context(__, action, arg) {
const { state } = get_request_store();
const { refreshes } = state;
if (!refreshes) {
const name = __.type === 'query_batch' ? `query.batch '${__.name}'` : `query '${__.name}'`;
throw new Error(
`Cannot call ${action} on ${name} because it is not executed in the context of a command/form remote function`
);
}
const cache = get_cache(__, state);
const cache_key = stringify_remote_arg(arg, state.transport);
const refreshes_key = create_remote_key(__.id, cache_key);
return { __, state, refreshes, refreshes_key, cache, cache_key };
}
/**
* @param {{ __: RemoteInfo; refreshes: Record<string, Promise<any>>; cache: Record<string, { serialize: boolean; data: any }>; refreshes_key: string; cache_key: string }} context
* @param {any} value
* @param {boolean} [is_immediate_refresh=false]
* @returns {Promise<void>}
*/
function update_refresh_value(
{ __, refreshes, refreshes_key, cache, cache_key },
value,
is_immediate_refresh = false
) {
const promise = Promise.resolve(value);
if (!is_immediate_refresh) {
cache[cache_key] = { serialize: true, data: promise };
}
if (__.id) {
refreshes[refreshes_key] = promise;
}
return promise.then(() => {});
}