Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quick-zebras-know.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

feat: allow query.set() to be called on the server
40 changes: 16 additions & 24 deletions documentation/docs/20-core-concepts/60-remote-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export const getPost = query(v.string(), async (slug) => {

Both the argument and the return value are serialized with [devalue](https://github.com/sveltejs/devalue), which handles types like `Date` and `Map` (and custom types defined in your [transport hook](hooks#Universal-hooks-transport)) in addition to JSON.

### Updating queries
### Refreshing queries

Any query can be re-fetched via its `refresh` method, which retrieves the latest value from the server:

Expand All @@ -170,29 +170,6 @@ Any query can be re-fetched via its `refresh` method, which retrieves the latest
</button>
```

Alternatively, if you need to update its value manually, you can use the `set` method:

```svelte
<script>
import { getPosts } from './data.remote';
import { onMount } from 'svelte';

onMount(() => {
const ws = new WebSocket('/ws');
ws.addEventListener('message', (ev) => {
const message = JSON.parse(ev.data);
if (message.type === 'new-post') {
getPosts().set([
message.post,
...getPosts().current,
]);
}
});
return () => ws.close();
});
</script>
```

> [!NOTE] Queries are cached while they're on the page, meaning `getPosts() === getPosts()`. This means you don't need a reference like `const posts = getPosts()` in order to update the query.

## form
Expand Down Expand Up @@ -293,6 +270,9 @@ import * as v from 'valibot';
import { error, redirect } from '@sveltejs/kit';
import { query, form } from '$app/server';
const slug = '';
const post = { id: '' };
/** @type {any} */
const externalApi = '';
// ---cut---
export const getPosts = query(async () => { /* ... */ });

Expand All @@ -308,6 +288,15 @@ export const createPost = form(async (data) => {
// Redirect to the newly created page
redirect(303, `/blog/${slug}`);
});

export const updatePost = form(async (data) => {
// form logic goes here...
const result = externalApi.update(post);

// The API already gives us the updated post,
// no need to refresh it, we can set it directly
+++await getPost(post.id).set(result);+++
});
```

The second is to drive the single-flight mutation from the client, which we'll see in the section on [`enhance`](#form-enhance).
Expand Down Expand Up @@ -564,6 +553,9 @@ export const addLike = command(v.string(), async (id) => {
`;

+++getLikes(id).refresh();+++
// Just like within form functions you can also do
// getLikes(id).set(...)
// in case you have the result already
});
```

Expand Down
3 changes: 2 additions & 1 deletion packages/kit/src/exports/public.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1805,7 +1805,8 @@ export type RemoteQuery<T> = RemoteResource<T> & {
/**
* On the client, this function will update the value of the query without re-fetching it.
*
* On the server, this throws an error.
* On the server, this can be called in the context of a `command` or `form` and the specified data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
set(value: T): void;
/**
Expand Down
26 changes: 22 additions & 4 deletions packages/kit/src/runtime/app/server/remote/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,32 @@ export function query(validate_or_fn, maybe_fn) {

const { event, state } = get_request_store();

const abort_controller = new AbortController();
/** @type {Promise<any> & Partial<RemoteQuery<any>>} */
const promise = get_response(__.id, arg, state, () =>
run_remote_function(event, state, false, arg, validate, fn)
const promise = get_response(
__.id,
arg,
state,
() => run_remote_function(event, state, false, arg, validate, fn),
abort_controller.signal
);

promise.catch(() => {});

promise.set = () => {
throw new Error(`Cannot call '${__.name}.set()' on the server`);
/** @param {Output} value */
promise.set = (value) => {
abort_controller.abort();
const { state } = get_request_store();
const refreshes = state.refreshes;

if (!refreshes) {
throw new Error(
`Cannot call set on query '${__.name}' because it is not executed in the context of a command/form remote function`
);
}

const cache_key = create_remote_cache_key(__.id, stringify_remote_arg(arg, state.transport));
refreshes[cache_key] = Promise.resolve(value);
};

promise.refresh = () => {
Expand All @@ -101,6 +118,7 @@ export function query(validate_or_fn, maybe_fn) {
};

promise.withOverride = () => {
abort_controller.abort();
throw new Error(`Cannot call '${__.name}.withOverride()' on the server`);
};

Expand Down
7 changes: 6 additions & 1 deletion packages/kit/src/runtime/app/server/remote/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,14 @@ export function create_validator(validate_or_fn, maybe_fn) {
* @param {any} arg
* @param {RequestState} state
* @param {() => Promise<T>} get_result
* @param {AbortSignal | undefined=} signal
* @returns {Promise<T>}
*/
export function get_response(id, arg, state, get_result) {
export async function get_response(id, arg, state, get_result, signal) {
if (signal) {
await new Promise((r) => setTimeout(r, 0));
if (signal.aborted) throw new DOMException('The operation was aborted.', 'AbortError');
}
Comment on lines +73 to +76
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's this for?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see — it means that the work is skipped if set is immediately called. Creating an AbortController feels like overkill to be honest, and I'd expect this to use queueMicrotask rather than setTimeout. Will tinker locally

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

await Promise.resolve() should do the trick, it's a Microtask, too

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

opened #14338

const cache_key = create_remote_cache_key(id, stringify_remote_arg(arg, state.transport));

return ((state.remote_data ??= {})[cache_key] ??= get_result());
Expand Down
15 changes: 12 additions & 3 deletions packages/kit/test/apps/basics/src/routes/remote/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
add,
get_count,
set_count,
set_count_server,
set_count_server_refresh,
set_count_server_set,
resolve_deferreds
} from './query-command.remote.js';
Expand Down Expand Up @@ -33,7 +34,7 @@
<p id="command-pending">Command pending: {set_count.pending}</p>
{/if}

<button onclick={() => set_count_server(0)} id="reset-btn">reset</button>
<button onclick={() => set_count_server_refresh(0)} id="reset-btn">reset</button>

<button onclick={() => count.refresh()} id="refresh-btn">Refresh</button>

Expand All @@ -57,7 +58,7 @@
</button>
<button
onclick={async () => {
command_result = await set_count_server(4);
command_result = await set_count_server_refresh(4);
}}
id="multiply-server-refresh-btn"
>
Expand All @@ -82,6 +83,14 @@
>
command (deferred)
</button>
<button
onclick={async () => {
command_result = await set_count_server_set(8);
}}
id="multiply-server-set-btn"
>
command (query server set)
</button>

<button id="refresh-all" onclick={() => refreshAll()}>refreshAll</button>
<button id="refresh-remote-only" onclick={() => refreshAll({ includeLoadFunctions: false })}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ export const add = query('unchecked', ({ a, b }) => a + b);
let count = 0;
const deferreds = [];

export const get_count = query(() => count);
let get_count_called = false;
export const get_count = query(() => {
get_count_called = true;
return count;
});

export const set_count = command('unchecked', async ({ c, slow = false, deferred = false }) => {
if (deferred) {
Expand All @@ -26,8 +30,19 @@ export const resolve_deferreds = command(() => {
deferreds.length = 0;
});

export const set_count_server = command('unchecked', (c) => {
export const set_count_server_refresh = command('unchecked', (c) => {
count = c;
get_count().refresh();
return c;
});

export const set_count_server_set = command('unchecked', async (c) => {
get_count_called = false;
count = c;
get_count().set(c);
await new Promise((resolve) => setTimeout(resolve, 100));
if (get_count_called) {
throw new Error('get_count should not have been called');
}
return c;
});
17 changes: 16 additions & 1 deletion packages/kit/test/apps/basics/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1308,7 +1308,7 @@
expect(page.locator('p.loadingfail')).toBeHidden();
});

test('Catches fetch errors from server load functions (direct hit)', async ({ page }) => {

Check warning on line 1311 in packages/kit/test/apps/basics/test/client.test.js

View workflow job for this annotation

GitHub Actions / test-kit (22, ubuntu-latest, chromium)

flaky test: Catches fetch errors from server load functions (direct hit)

retries: 2
page.goto('/streaming/server-error');
await expect(page.locator('p.eager')).toHaveText('eager');
await expect(page.locator('p.fail')).toHaveText('fail');
Expand Down Expand Up @@ -1667,6 +1667,7 @@

await page.click('#set-btn');
await expect(page.locator('#count-result')).toHaveText('999 / 999 (false)');
await page.waitForTimeout(100); // allow all requests to finish (in case there are query refreshes which shouldn't happen)
expect(request_count).toBe(0);
});

Expand Down Expand Up @@ -1710,7 +1711,7 @@
expect(request_count).toBe(1); // no query refreshes, since that happens as part of the command response
});

test('command does server-initiated single flight mutation', async ({ page }) => {
test('command does server-initiated single flight mutation (refresh)', async ({ page }) => {
await page.goto('/remote');
await expect(page.locator('#count-result')).toHaveText('0 / 0 (false)');

Expand All @@ -1724,6 +1725,20 @@
expect(request_count).toBe(1); // no query refreshes, since that happens as part of the command response
});

test('command does server-initiated single flight mutation (set)', async ({ page }) => {
await page.goto('/remote');
await expect(page.locator('#count-result')).toHaveText('0 / 0 (false)');

let request_count = 0;
page.on('request', (r) => (request_count += r.url().includes('/_app/remote') ? 1 : 0));

await page.click('#multiply-server-set-btn');
await expect(page.locator('#command-result')).toHaveText('8');
await expect(page.locator('#count-result')).toHaveText('8 / 8 (false)');
await page.waitForTimeout(100); // allow all requests to finish (in case there are query refreshes which shouldn't happen)
expect(request_count).toBe(1); // no query refreshes, since that happens as part of the command response
});

test('command does client-initiated single flight mutation with override', async ({ page }) => {
await page.goto('/remote');
await expect(page.locator('#count-result')).toHaveText('0 / 0 (false)');
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1781,7 +1781,8 @@ declare module '@sveltejs/kit' {
/**
* On the client, this function will update the value of the query without re-fetching it.
*
* On the server, this throws an error.
* On the server, this can be called in the context of a `command` or `form` and the specified data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
set(value: T): void;
/**
Expand Down
Loading