SDK client and cache-first query
In this chapter you read the chapter 2 orders.list read-model from the Fresh app. The SDK gives you
a typed client built from the same contract, and a query factory that wraps every procedure in a
KV-backed stale-while-revalidate (SWR) cache: the queue paints from the last-known rows, even while
the orders service redeploys, and refreshes in the background. The SWR behavior belongs to the
callable procedure action (for example, await ordersQueries.list(input)); getCachedEntry(input)
is a separate KV-only metadata read and never schedules a refresh.
- 1 · Scaffold
- 2 · Contract to service
- 3 · Cache-first query
- 4 · definePage + island
- 5 · Live stream
- 6 · Deploy
Choose how an open screen gets fresh data
| Screen needs | Mechanism | What wakes the open screen | Authorization |
|---|---|---|---|
| Show changes as they happen, even while the user is idle | Subscribe with a Fresh Streams reader and render the live collection with useLiveQuery. |
The next committed stream update changes the live collection and rerenders the island. Dispose the reader when the island unmounts. | Authorize the stream and replay on each connection. Use a per-request reader credential resolver so reconnects use current credentials. The shipped Streams service checks authorization when a request starts and does not re-check an open SSE response: disposing a browser reader cleans up the client rather than enforcing revocation (server-side revocation is tracked in #2146). |
| Refresh on a schedule when a short delay is acceptable | Use useIslandQuery with the SDK query options and interval, such as 15 seconds for a visible dashboard. Leave background polling disabled. |
The interval triggers a typed read and the result updates the mounted query. A failed or suspended poll can delay the update. | Check current access on every poll. Resolve the credential at request time and clear private query state when the session or account changes. |
| Refresh on the next read or when the user returns | Call the SDK query action, such as ordersQueries.list(input), from an authorized server read. It can return a stale cached value while refreshing KV in the background. |
A new read, navigation, or a focus refetch (using a query client built with refetchOnWindowFocus: true, or a visibility handler calling refetch()) triggers the screen's read path. Fresh's default disables focus refetch. A KV refresh alone leaves the open screen as it was. |
Authorize before reading cached data and again at the service on revalidation. Partition private cached data by non-secret access scope, or use a direct-only client when it cannot be shared safely. |
The orders examples in this chapter use the public synthetic read-model from
chapter 2. For protected procedures, use the
SDK's typed bearer contribution with a resolver
that reads the current session instead of capturing a token at mount time. Browser
queryOptions() calls the typed client directly, so a browser refetch reaches server-side SWR only
when its server read invokes the callable action. getCachedEntry() reads KV metadata and never
starts revalidation.
What you will build
One module, apps/dashboard/lib/orders.ts, that exports a typed ordersClient and an
ordersQueries query utility. The client is derived from typeof ordersContract, so
ordersClient.list({ … }) is type-checked against the chapter 2 contract. The query factory adds
per-procedure helpers (queryOptions(), clientKey() and the KV-only getCachedEntry() metadata
read) that chapters 4 and 5 build the page on.
Before you begin
You need chapter 2's orders service answering
at its allocated endpoint, the database seeded, and aspire start up. Confirm the read-model returns data:
netscript service list
netscript contract inspect orders
Use list_api_services → list_service_operations → get_operation_schema for the live
operation. The typed client in Step 1 calls it with { limit: 1, offset: 0 }.
The query should return one seeded order. If items is empty, re-run netscript db seed from the workspace
root.
Step 1 — Create the typed service client
createServiceClient from @netscript/sdk/client builds a client from a contract. It takes the
contract and a serviceName, the discovery key the client uses to find the service's URL at
call time. Create the module in your Fresh app:
// apps/dashboard/lib/orders.ts
import { ordersContract } from '@my-dashboard/contracts';
import { createServiceClient } from '@netscript/sdk/client';
import { createQueryFactories } from '@netscript/sdk/query';
export const ordersClient = createServiceClient<typeof ordersContract>({
contract: ordersContract,
serviceName: 'orders',
});
ordersClient.list(input) has the exact signature the contract declares: a wrong input shape, or
reading a field the output doesn't have, is a compile error.
Step 2 — Add the cache-first query factory
A bare client calls the service every time. A dashboard wants cache-first reads: serve the
last-known answer immediately, then revalidate in the background. createQueryFactories wraps each
procedure in a KV-backed stale-while-revalidate layer. Add it to the same module:
// apps/dashboard/lib/orders.ts (add below the client)
// Server-side query factories — callable actions use KV-backed stale-while-revalidate.
export const ordersQueries = createQueryFactories({
orders: { contract: ordersContract, client: ordersClient },
}).orders;
The callable procedure action owns that stale policy. getCachedEntry(input) only inspects the KV
value and timestamp; it doesn't run the policy.
ordersQueries has one entry per contract procedure (list, getById, getStats, …), each a
small object of typed helpers. The next chapters use four of them:
| Name · Type | Description |
|---|---|
.queryOptions(input)(input) => options |
A TanStack Query options object (queryKey + queryFn) for the client island — chapter 4 passes it straight to useQuery. |
.clientKey(input?)(input?) => key |
The stable query key the client uses to read, write, and invalidate this procedure's cache. |
.getCachedEntry(input)(input) => Promise<entry | null> |
Server-side KV metadata read: resolves to { data, cachedAt } from KV, or null on a cold cache. It does not evaluate staleness or fetch. |
.key(input)(input) => key |
The server-side KV cache key for the entry. |
Step 3 — Understand the calling shapes
You now have two ways to read orders, for two places in the stack:
- Server, policy-aware cache read — first run
const data = await ordersQueries.list(input, { preferFreshOnStale: true }), then readconst entry = await ordersQueries.list.getCachedEntry(input)and returnentry ?? { data, cachedAt: Date.now() }. The metadata read alone never fetches or revalidates. The default callable action without the flag is the non-blocking SWR path; this loader choosespreferFreshOnStale: truesocachedAtreflects the refreshed value. - Client, in an island —
useQuery(ordersQueries.list.queryOptions(input))inside a Fresh island. Used in chapter 4'sQueryIslandfor client-side reads and refetch.
Both take their types and their cache key from the same contract, so a server-rendered row and a client-refetched row have the same shape.
Verify your progress
Type-check the workspace to confirm the client and query factory line up with the contract:
deno task check
A clean check confirms createServiceClient<typeof ordersContract> and the query factory take their
types from your chapter 2 contract. Leave aspire start up: the next chapter renders the page that
calls through this client, and a missing services__orders__http__0 shows up there as a
"Service URL not found" error.
- [ ]
apps/dashboard/lib/orders.tsexportsordersClientandordersQueries. - [ ]
deno task checkis clean. - [ ]
deno check apps/dashboard/lib/orders.ts --unstable-kvpasses on its own — the module compiles against the chapter-2 contract with no other file in play.
What you built
A typed ordersClient and a cache-first ordersQueries query layer, both derived from the chapter 2
contract, with service discovery resolving the URL. Next, you render the table with NetScript's
definePage builder and a QueryIsland that hydrates these query helpers in the browser.