@molecule/app-query
Core interface · query · App (browser) · v1.5.0 · Apache-2.0
Client-side data cache and prefetch core interface for molecule.dev — fetch once, read synchronously, warm ahead of navigation; the cache engine is a bond
npm install @molecule/app-queryHow it works
@molecule/app-query is the query core interface on the app (browser) side: the API your app calls, with no vendor inside.
Choose the implementation by bonding one of its 2 providers: @molecule/app-query-memory, @molecule/app-query-tanstack.
import { getClient } from '@molecule/app-http'
import { getQueryClient, setProvider } from '@molecule/app-query'
import { provider } from '@molecule/app-query-tanstack'
setProvider(provider)
const packageQuery = (name: string) => ({
key: ['package', name],
fetch: async (signal: AbortSignal) =>
(await getClient().get(`/data/packages/${encodeURIComponent(name)}.json`, { signal })).data,
})
const client = getQueryClient()
client.prefetch(packageQuery('api-auth')) // on hover: warm it
const doc = client.get(['package', 'api-auth']) // later, synchronously
await client.fetch(packageQuery('api-auth')) // or wait for it
client.invalidate(['package']) // every package is stale nowProviders (2): @molecule/app-query-memory, @molecule/app-query-tanstack
Works with: @molecule/app-bond
Reference
Client-side query cache core interface for molecule.dev.
One in-memory cache of documents the app fetches — a package page, a
profile, a list — keyed by value, read synchronously, warmed ahead of a
navigation, and observed by components. Bond a provider (e.g.
@molecule/app-query-tanstack) at startup, then use
getQueryClient anywhere; @molecule/app-query-react adds the hooks.
A query with keepPreviousData: true must provide principal. The type rejects a missing
principal before an observer can fail at runtime. Pass the viewer's stable ID (also in the
query key), or 'public' when the response is identical for every viewer.
For a contract-backed app, use the generated client in src/resources/.
mlcl resources --contract <path> generates the supported client for the
routes in that contract. Import its named reads, writes and record views.
They use the bonded auth session automatically, pause reads while it settles,
and share a public cache when there is no auth bond. A successful write
publishes the saved detail or deletion and refetches up to four recently
read lists for that resource and session. Query failures appear in error,
and writes reject with the original HTTP error. Use the generated
<record>ErrorMessage(error) helper to display the contract's validation
message or a generic fallback.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { getClient } from '@molecule/app-http'
import { getQueryClient, setProvider } from '@molecule/app-query'
import { provider } from '@molecule/app-query-tanstack'
setProvider(provider)
const packageQuery = (name: string) => ({
key: ['package', name],
fetch: async (signal: AbortSignal) =>
(await getClient().get(`/data/packages/${encodeURIComponent(name)}.json`, { signal })).data,
})
const client = getQueryClient()
client.prefetch(packageQuery('api-auth')) // on hover: warm it
const doc = client.get(['package', 'api-auth']) // later, synchronously
await client.fetch(packageQuery('api-auth')) // or wait for it
client.invalidate(['package']) // every package is stale now
Type
core
Installation
npm install @molecule/app-query @molecule/app-bond
API
Interfaces
ResourceResponse
The part of an HTTP response a resource reads.
interface ResourceResponse {
/** The parsed response body. */
data: unknown
}
ResourceHttp
The HTTP client a resource calls: the app's own bonded client (getClient() from
@molecule/app-http) has this shape. Only what a resource uses is named here.
interface ResourceHttp {
/** Reads `path`; `signal` cancels it and `params` become the query string. */
get(
path: string,
options?: { signal?: AbortSignal; params?: Record<string, unknown> },
): Promise<ResourceResponse>
/** Creates at `path`. */
post(path: string, body?: unknown): Promise<ResourceResponse>
/** Replaces at `path`. */
put(path: string, body?: unknown): Promise<ResourceResponse>
/** Changes part of the record at `path`. */
patch(path: string, body?: unknown): Promise<ResourceResponse>
/** Removes at `path`. */
delete(path: string): Promise<ResourceResponse>
}
QueryResourceConfig
What createQueryResource needs to know about one resource.
interface QueryResourceConfig<T> {
/** The first element of every cache key of this resource, e.g. `'invoices'`. */
name: string
/** The collection's path under the API base, e.g. `'/invoices'`. */
path: string
/** The app's HTTP client, read on every call so a client bonded later is the one used. */
http: () => ResourceHttp
/** The field a record is addressed by in a URL. Defaults to `'id'`. */
id?: keyof T & string
/** The HTTP method the API updates a record with. Defaults to `'put'`. */
updateMethod?: 'put' | 'patch'
/** Reads the records out of a list response. Defaults to the body itself. */
readList?: (response: ResourceResponse) => T[]
/** Reads the record out of a detail or write response. Defaults to the body itself. */
readOne?: (response: ResourceResponse) => T | null
}
QueryResource
The reads and writes createQueryResource returns.
interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
/**
* `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
* or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
* One record per URL identity, retaining the first occurrence. Equal values without an
* addressable id remain separate. Writes already refresh the collection.
*/
list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
/**
* Options for a collection's whole page (rows plus totals), or a filtered collection path.
* Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
* canonical page response for `path`; row-only `list` reads keep a separate cache entry.
* Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
* immediately and keep stale list responses from restoring them.
*/
listPage<Page>(
viewer: string,
params: Record<string, unknown>,
readPage: (response: ResourceResponse) => Page,
path?: string,
removeFromPage?: (page: Page, id: string) => Page,
): QueryOptions<Page>
/**
* `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
* observes nothing). An empty ID is also unknown. A missing record resolves to null.
*/
detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
/** Creates a record, shows it in the cache and refreshes the lists on screen. */
create(viewer: string, input: Create): Promise<T>
/** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
update(viewer: string, id: string, input: Update): Promise<T>
/** Removes a record from detail and tracked row lists, then refreshes those lists. */
remove(viewer: string, id: string): Promise<void>
/**
* Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
* `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
* of `useOptimisticValue`. Rejects an absent or empty record ID before sending a request.
* The saved detail is published before tracked lists finish refreshing; this promise waits
* for those refreshes. Render the shared controller's value and let it queue inverse clicks
* during that interval. A page-local busy guard can drop a click on the newly changed label.
*/
toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
/** Fetches the lists on screen again, after a change this resource did not make itself. */
refresh(viewer: string): Promise<void>
}
QueryState
One document's state, as observers see it.
interface QueryState<T> {
/** The document, when it has ever been loaded or set. */
data: T | undefined
/** `idle` before anything happened, `loading` with nothing cached yet, then `success` or `error`. */
status: QueryStatus
/**
* The last fetch's error, when `status` is `error`. A `fetch` that rejects with something other
* than an `Error` is reported as an `Error` whose `cause` is that value, so `error.message` is
* always readable.
*/
error: Error | undefined
/** A fetch is in flight (also while stale data is shown). */
isFetching: boolean
/** When `data` was last written, in milliseconds since the epoch. */
updatedAt: number | undefined
/**
* `true` while `data` is the previous key's document, retained by
* `QueryOptions.keepPreviousData` for the same `principal`. It is never set for data
* that belongs to another principal, and it clears as soon as the observed key answers or
* fails. An empty state describes the key on screen: do not render one while this is set.
*/
isPreviousData?: boolean
}
QueryClient
The cache. One per app (see getQueryClient), shared by every page.
interface QueryClient {
/**
* The cached document, synchronously, whether fresh or stale. Never fetches.
*
* @param key - The document's key.
* @returns The document, or `undefined` when nothing is cached.
*/
get<T>(key: QueryKey): T | undefined
/**
* The document's full state, synchronously.
*
* @param key - The document's key.
* @returns The state; `idle` with no data for an unknown key.
*/
getState<T>(key: QueryKey): QueryState<T>
/**
* The document: resolved at once when cached and fresh, shared with a
* fetch already in flight, otherwise fetched and cached. Rejects when the
* fetch fails; a failure is never cached, so the next call tries again.
*
* @param options - Key, fetch, freshness.
* @returns The document.
*/
fetch<T>(options: QueryOptions<T>): Promise<T>
/**
* Warms the cache for a document likely to be needed next. Never throws
* and never rejects; does nothing when the document is cached and fresh
* or already being fetched.
*
* @param options - Key, fetch, freshness.
*/
prefetch<T>(options: QueryOptions<T>): void
/**
* Seeds the cache, for example from a JSON island the server rendered, or
* with the server's own answer to a mutation.
*
* Subscribed observers receive the document at once, and the next `fetch`
* or `subscribe` treats it as fresh (no refetch) until it goes stale.
*
* `set` supersedes a fetch already in flight for this exact key: that fetch cannot later
* overwrite this document or its state, and `isFetching` becomes false. A `fetch()` promise
* already returned still settles independently of this write; read `get` when the
* newest cached document is needed.
*
* @param key - The document's key.
* @param data - The document.
*/
set<T>(key: QueryKey, data: T): void
/**
* Marks the document, and every document whose key starts with this key,
* as stale: the next `fetch` or `subscribe` refetches it.
*
* An observer that is already subscribed keeps what it has — the cached
* document, or the error — and is NOT refetched. To retry into a mounted
* page, call `fetch` with the same options, or subscribe again (a
* key change or a re-mount). `set` shows a mutation's own response
* without a round trip.
*
* @param key - A key or a key prefix.
*/
invalidate(key: QueryKey): void
/**
* Observes a document: emits its state now and on every change, starting
* a fetch when the document is absent or stale.
*
* @param options - Key, fetch, freshness.
* @param listener - Called with each state.
* @returns Stops observing.
*/
subscribe<T>(options: QueryOptions<T>, listener: (state: QueryState<T>) => void): () => void
/** Drops every document and every in-flight fetch. */
clear(): void
}
QueryClientConfig
Defaults a client applies to every query that does not say otherwise.
interface QueryClientConfig {
/** Default freshness. Defaults to 5 minutes. */
staleMs?: number
/** TanStack Query's name for `QueryClientConfig.staleMs`; `staleMs` wins when both are set. */
staleTime?: number
/** Default time an unused document stays in memory. Defaults to 30 minutes. */
gcMs?: number
/** TanStack Query's name for `QueryClientConfig.gcMs`; `gcMs` wins when both are set. */
gcTime?: number
}
QueryProvider
Query provider interface. All query bonds implement this.
interface QueryProvider {
/** Provider name identifier (e.g. `'tanstack'`, `'memory'`). */
readonly name: string
/**
* Creates a cache.
*
* @param config - Defaults for every query.
* @returns A client.
*/
createClient(config?: QueryClientConfig): QueryClient
}
Types
QueryKey
A query key: an array of parts, compared by value (['package', 'api-auth']
equals another ['package', 'api-auth']; an object part equals another with
the same entries). A key PREFIXES every longer key that starts with its
parts, which is what QueryClient.invalidate uses.
type QueryKey = readonly unknown[]
QueryOptions
How one document is fetched and how long it stays fresh.
type QueryOptions<T> = {
/** What identifies the document. */
key: QueryKey
/**
* Loads the document. The signal aborts when nobody wants the result any more: the last
* observer unsubscribed (the page unmounted or switched key) and no `fetch()` caller still
* awaits it, or the client was cleared. A bond must honour it — never ignore the signal in an
* `options.fetch` the app supplies, or the request keeps running for a page that is gone.
*/
fetch: (signal: AbortSignal) => Promise<T>
/**
* Pure, idempotent projection applied to fetched and explicitly set documents before
* observers receive them. A key has one data contract: use the same projection for
* every observer of that key. The bond remembers it until the cache entry is collected.
* Resource row lists use this to keep one record per URL identity, including when a
* caller inserts a mutation response which the resource has already refreshed.
* Ordinary queries without a projection preserve their data, including duplicates.
*
* Declared as a method so options stay covariant in `T`: a `QueryOptions<A>` is still a
* `QueryOptions<A | B>`, as `fetch` alone makes it. The bond only ever passes it the
* documents of its own key.
*/
normalizeData?(data: T): T
/** How long a cached document is fresh (no refetch). Defaults to the client's, then 5 minutes. */
staleMs?: number
/** TanStack Query's name for `QueryOptions.staleMs`; `staleMs` wins when both are set. */
staleTime?: number
/** How long an unused document stays in memory. Defaults to the client's, then 30 minutes. */
gcMs?: number
/** TanStack Query's name for `QueryOptions.gcMs`; `gcMs` wins when both are set. */
gcTime?: number
/**
* Whether an observer hook should subscribe and fetch this query (TanStack Query's option;
* defaults to `true`). Passing `enabled: false` behaves identically to passing `null` to
* `useQuery`: no subscription, no fetch, and `status: 'idle'`.
*/
enabled?: boolean
/**
* Whose answer the document is: the viewer the request is made for, as a stable id — the
* signed-in principal's `String(user.id)`, or `'anonymous'` while signed out — whenever the
* server can filter or personalize the response by the session the app's HTTP client sends;
* `'public'` only for an endpoint that answers every viewer the same. Put the same value in the
* key: the cache serves a key's document to whoever observes it, so a viewer-dependent key must
* name the viewer. Required with `keepPreviousData` — it lets an observer keep one key's
* document on screen while the next key loads and drop it the moment the principal changes, so
* a principal switch never carries the previous principal's document into the next key.
*/
principal?: string
/**
* Observers may keep showing the document of the PREVIOUS key while a changed key loads, so a
* page, filter or view change does not blank an already-rendered list. The previous document is
* used only while the new key has no answer of its own: a completed response (including an empty
* list) or a failure shows the new key's state, and a changed `principal` drops it at once.
* Requires `principal`. Do not use it to carry one resource's document into another
* resource; a different screen is a different component (and a different hook instance).
*
* TypeScript requires `principal` whenever this can be `true`, including a dynamic boolean.
* Applies to observers (`useQuery` in `@molecule/app-query-react`); the cache itself never
* returns another key's document. Defaults to `false`.
*/
keepPreviousData?: boolean
} & ({ keepPreviousData?: false } | { principal: string })
QueryStatus
Where a document stands.
type QueryStatus = 'idle' | 'loading' | 'success' | 'error'
Functions
hashQueryKey(key)
A stable string for a key: object parts are serialized with their entries
sorted, so { a: 1, b: 2 } and { b: 2, a: 1 } hash the same; undefined
parts hash as null.
function hashQueryKey(key: QueryKey): string
key— The key.
Returns: Its string form.
keyStartsWith(key, prefix)
Whether key starts with every part of prefix (compared by value).
function keyStartsWith(key: QueryKey, prefix: QueryKey): boolean
key— The longer key.prefix— The shorter key.
Returns: true when prefix prefixes key (a key prefixes itself).
shouldPrefetch()
Whether it is reasonable to load something the person has not asked for
yet: false under the browser's data-saver setting or on a 2G-class
connection, true otherwise (including where the browser reports nothing).
function shouldPrefetch(): boolean
Returns: Whether to prefetch.
whenIdle(fn, timeout)
Runs fn when the browser is idle, or after timeout milliseconds at the
latest; where idle callbacks do not exist, after a short delay.
function whenIdle(fn: () => void, timeout?: number): () => void
fn— What to run.timeout— The longest wait, in milliseconds. Defaults to 2000.
Returns: Cancels the run if it has not happened yet.
prefetchQuery(options)
Warms the cache for a document, when the connection can afford it (see
shouldPrefetch() in the core). Safe to call repeatedly: a fresh or
in-flight document is skipped, and failures are swallowed.
function prefetchQuery<T>(options: QueryOptions<T>): void
options— Key, fetch, freshness.
setProvider(provider)
Registers a query provider as the active singleton. Called by bond
packages (e.g. @molecule/app-query-tanstack) during app startup.
function setProvider(provider: QueryProvider): void
provider— The query provider implementation to bond.
getProvider()
Retrieves the bonded query provider, throwing if none is configured.
function getProvider(): QueryProvider
Returns: The bonded query provider.
hasProvider()
Checks whether a query provider is currently bonded.
function hasProvider(): boolean
Returns: true if a query provider is bonded.
configureQueryClient(config)
Sets the defaults the shared client is created with. Call before the first
getQueryClient; later calls take effect after resetQueryClient.
function configureQueryClient(config: QueryClientConfig | undefined): void
config— Defaults for every query.
getQueryClient()
The app's one cache, created by the bonded provider on first use and reused afterwards, so every page reads and warms the same documents.
function getQueryClient(): QueryClient
Returns: The shared client.
resetQueryClient()
Forgets the shared client (its next use creates a new one). Tests only.
function resetQueryClient(): void
createQueryResource(config)
Describe one API resource once and get its reads and writes on the shared cache.
A page that loads with fetch inside an effect and mirrors the answer into useState has to
re-solve the same problems on every screen: a late answer for the previous page lands
over the current one, and a list still shows what it showed before a comment was added.
Here the reads are useQuery options (one key per
viewer, page and filter; the previous rows stay until the next answer) and every write puts
the server's own record into the cache and fetches the lists on screen again.
The factory supplies data operations. Mount a keyed
control inside QueryContent (your framework's query package: @molecule/app-query-react,
-vue, …) so it receives a loaded record and stays mounted during refresh.
For a server-backed toggle, use useOptimisticValue from your framework binding
(@molecule/app-react, @molecule/app-vue, …), or OptimisticToggleButton from its UI
package (@molecule/app-ui-react, …) for a boolean. Pass toggle as its
commit adapter, return the saved flag/count, and render the controller's value for the action
label too. Do not block clicks while that commit is pending. The resource example in
@molecule/app-query-react composes these APIs; a custom handler must provide the same
readiness and ordering itself.
Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client and the query provider are whatever the app bonded.
function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
config: QueryResourceConfig<T>,
): QueryResource<T, Create, Update>
config— The resource's name, path, HTTP client and response readers.
Returns: List and detail query options, and create, update, remove, toggle and refresh.
Available Providers
| Provider | Package |
|---|---|
| In-memory (no persistence) | @molecule/app-query-memory |
| TanStack Query | @molecule/app-query-tanstack |
Injection Notes
Requirements
Peer dependencies:
@molecule/app-bond^1.0.1
Runtime Dependencies
-
@molecule/app-bond -
A relationship modeled as POST to enable and DELETE to disable already has a client:
createQueryResource(config).toggle(viewer, id, action, desired)sends POST fortrueand DELETE forfalse, then returns the server's saved record.desiredis the value wanted AFTER the request. Record writes require a nonempty ID and reject a missing ID before dispatch. Mount the action with an identified record from the detail query. A boolean PUT/PATCH body or an API with different action semantics usesupdate()or its own explicit adapter instead.const members = createQueryResource<Member>({ name: 'members', path: '/members', id: 'username', http: getClient, readOne: (response) => (response.data as { member: Member }).member, }) const saved = await members.toggle(viewerId, username, 'watch', desired) // Return saved.watching from a boolean control's commit; use the saved record // with useOptimisticValue when the flag has a related count. A reload reads // the persisted server answer, so test both directions and revisit the page.Resource mutations publish the saved detail and refresh that viewer's tracked lists, including mounted observers. A raw HTTP write does not publish its response into this cache.
invalidate(key)only marks reads stale; it does not refresh a page already on screen. Use the resource mutation, or explicitlysetits canonical response andfetcheach affected query for a custom API. A page-localonChangedcallback is unnecessary when the resource owns the write. -
createQueryResource().list()owns a collection of records addressed by their URL id. It keeps the first occurrence of each identity on fetched and explicitly set lists; equal labels on different records and rows without an id remain intact. Resource writes already refresh these lists: render the query directly after awaitingcreate, without appending its return value again. Ordinary queries and opaquelistPage()envelopes preserve application-owned occurrence semantics. Query bonds applynormalizeDatabefore publishing any fetched or explicitly set document. A list used as a filter catalogue must keep every returned choice reachable. Render its returned rows, or expose explicit pagination/More; silently slicing the first few rows hides valid filters as the catalogue grows. Server-requested limits and deliberately curated previews remain application choices. -
Page data goes through a query, not a hand-written
useEffect+fetch. In React, useuseQueryfrom@molecule/app-query-react: it keeps one request per key, stable across re-renders, and aborts it only when the key changes or the page unmounts. An effect that cancels its own request on cleanup (acancelledflag or anAbortController) and whose deps include a function rebuilt each render cancels its request on every re-render and then skips the refetch — the response is dropped on a remote server and never on localhost. -
This is a browser cache, not a store. It holds what was fetched, for as long as it is useful; it is not where app state lives (see
@molecule/app-state) and it never persists. -
Keys are compared by value.
['package', 'api-auth']twice is one document; object parts compare by their entries. Put everything the fetch depends on into the key, or two different requests share one cache slot. -
get()returns stale data too. That is the point — a page paints what it has at once — whilesubscribe()refetches in the background. CheckupdatedAtif freshness matters for a display. -
A failed fetch is never cached, so retrying is one more
fetch().prefetch()swallows failures on purpose: the real navigation reports them. The bonded HTTP client rejects non-2xx responses. Nativefetchresolves them, so a custom fetcher must checkresponse.okbefore reading JSON; otherwise an error response becomes a successfully cached document. -
Prefetch with intent (pointer enter, focus, touch start) and while idle, and only when
shouldPrefetch()allows: a person on a metered or 2G connection did not ask for the page they hovered. -
Use one client per app (
getQueryClient()); a second client is a second cache that knows nothing about the first.
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:
- Opening a detail page after hovering its link shows no loading state (the document was warmed) and the page is the right one.
- Opening the same page twice fetches it once (check the network panel).
- Going back to a page painted earlier paints at once, from memory.
- After the app invalidates a key (an edit, a refresh action), the next view shows the new data.
- With the browser's data-saver on, hovering links fetches nothing.