query-layer
$
npx mdskill add EpicenterHQ/epicenter/query-layerManages reactive data fetching and mutation with TanStack Query
- Solves UI data consistency and caching for async service calls
- Uses TanStack Query, Svelte, and runtime DI for state management
- Applies error transformation and toast-on-error patterns for user feedback
- Delivers reactive query results to components via hooks and DI
SKILL.md
.github/skills/query-layerView on GitHub ↗
---
name: query-layer
description: Query layer with TanStack Query, error transformation, runtime DI. Use for createQuery, createMutation, queries/mutations, reactive data management.
metadata:
author: epicenter
version: '2.0'
---
# Query Layer Patterns
## Reference Repositories
- [TanStack Query](https://github.com/tanstack/query) — Async state management for data fetching
## Upstream Grounding
When TanStack Query behavior, Svelte adapter types, cache invalidation semantics, optimistic updates, or mutation lifecycle callbacks affect correctness, ask DeepWiki a narrow question against `tanstack/query` before relying on memory. Use it to orient, then verify decisive details against local installed types, source, or official docs before changing code.
Skip DeepWiki for stable basics and repo-local patterns already documented below.
The query layer is the reactive bridge between UI components and the service layer. It wraps pure service functions with caching, reactivity, and state management using TanStack Query and WellCrafted factories.
> **Related Skills**: See `services-layer` for the service layer these queries consume. See `svelte` for Svelte-specific TanStack Query patterns. See `error-handling` for toast-on-error patterns—how errors from Results surface to users via `toastOnError` and `extractErrorMessage`.
## When to Apply This Skill
Use this pattern when you need to:
- Create queries or mutations that consume services
- Transform service-layer errors into user-facing error types
- Implement runtime service selection based on user settings
- Add optimistic cache updates for instant UI feedback
- Understand the dual interface pattern (reactive vs imperative)
## Core Architecture
```
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
│ UI │ --> │ RPC/Query │ --> │ Services │
│ Components │ │ Layer │ │ (Pure) │
└─────────────┘ └─────────────┘ └──────────────┘
↑ │
└────────────────────┘
Reactive Updates
```
**Query Layer Responsibilities:**
- Call services with injected settings/configuration
- Transform service errors to user-facing error types for display
- Manage TanStack Query cache for optimistic updates
- Provide dual interfaces: reactive (`.options`) and imperative (`.execute()`)
## Error Transformation Pattern
**Critical**: Service errors should be transformed to user-facing error types at the query layer boundary.
### Three-Layer Error Flow
```
Service Layer → Query Layer → UI Layer
TaggedError<'Name'> → UserFacingError → Toast notification
(domain-specific) (display-ready) (display)
```
### Standard Error Transformation
```typescript
import { Err, Ok } from 'wellcrafted/result';
// In query layer - transform service error to user-facing error
const { data, error } = await services.recorder.startRecording(params);
if (error) {
return Err({
title: '❌ Failed to start recording',
description: error.message,
action: { type: 'more-details', error },
});
}
return Ok(data);
```
## Dual Interface Pattern
Every query/mutation provides two ways to use it:
### Reactive Interface: `.options`
Use in Svelte components for automatic state management. Pass `.options` (a static object) inside an accessor function:
```svelte
<script lang="ts">
import { createQuery, createMutation } from '@tanstack/svelte-query';
import { rpc } from '$lib/query';
// Reactive query - wrap in accessor function, access .options (no parentheses)
const recorderState = createQuery(() => rpc.recorder.getRecorderState.options);
// Reactive mutation - same pattern
const transformRecording = createMutation(
rpc.transformer.transformRecording.options,
);
</script>
{#if recorderState.isPending}
<Spinner />
{:else if recorderState.error}
<Error message={recorderState.error.description} />
{:else}
<RecorderIndicator state={recorderState.data} />
{/if}
```
### Imperative Interface: `.execute()` / `.fetch()`
Use in event handlers and workflows without reactive overhead:
```typescript
// In an event handler or workflow
async function handleTransform(recordingId: string, transformation: Transformation) {
const { error } = await rpc.transformer.transformRecording({
recordingId,
transformation,
});
if (error) {
notify.error(error);
return;
}
notify.success({ title: 'Transformation complete' });
}
// In a sequential workflow
async function stopAndTranscribe(toastId: string) {
const { data: blobData, error: stopError } =
await rpc.recorder.stopRecording({ toastId });
if (stopError) {
notify.error(stopError);
return;
}
// Continue with transcription...
}
```
### When to Use Each
| Use `.options` with createQuery/createMutation | Use `.execute()`/`.fetch()` |
| ---------------------------------------------- | --------------------------- |
| Component data display | Event handlers |
| Loading spinners needed | Sequential workflows |
| Auto-refetch wanted | One-time operations |
| Reactive state needed | Outside component context |
| Cache synchronization | Performance-critical paths |
## Key Rules
1. **Always transform errors at query boundary** - Never return raw service errors
2. **Use `.options` (no parentheses)** - It's a static object, wrap in accessor for Svelte
3. **Never double-wrap errors** - Each error is wrapped exactly once
4. **Services are pure, queries inject settings** - Services take explicit params
5. **Use imperative calls in `.ts` files** - `createMutation` requires component context
6. **Update cache optimistically** - Better UX for mutations
## References
Load these on demand based on what you're working on:
- If working with **error transformation examples and anti-patterns**, read [references/error-transformation-patterns.md](references/error-transformation-patterns.md)
- If working with **runtime dependency injection and service selection**, read [references/runtime-dependency-injection.md](references/runtime-dependency-injection.md)
- If working with **cache management, query definitions, RPC namespace, or notify coordination**, read [references/advanced-query-patterns.md](references/advanced-query-patterns.md)
- See `apps/whispering/src/lib/query/README.md` for detailed architecture
- See the `services-layer` skill for how services are implemented
- See the `error-handling` skill for trySync/tryAsync patterns and toast-on-error conventions
More from EpicenterHQ/epicenter
- agent-goalWrite `/goal` prompts for long-running agent work in Codex or Claude Code. Use for slash goal, agent goal, durable objective, autonomous coding run.
- approachability-auditReview code as a new TypeScript developer. Use when code feels indirect, clever, hard to follow, or needs a pass on abstractions, names, first-read clarity.
- arktypeArktype: runtime validation, discriminated unions with .merge()/.or(), spread keys. Use when mentioning arktype, type(), union types, command/event schemas.
- attach-primitiveContract and invariants for `attach*` composition primitives in `packages/workspace` (side-effectful building blocks like attachIndexedDb, attachSqlite, attachBroadcastChannel, attachEncryption, attachTable, openCollaboration), and when to use `create*` (pure construction) instead. Use when writing or reviewing an `attach*` or `create*` function, naming a new workspace primitive, composing inside a workspace builder, or deciding whether a primitive registers listeners at call time.
- authEpicenter auth packages: `@epicenter/auth`, `@epicenter/auth-svelte`, OAuth sessions, identity state, auth-owned fetch/WebSocket, and workspace lifecycle binding. Use when editing Epicenter auth clients, session state, hosted sign-in, or auth/workspace integration.
- autumnAutumn billing in Epicenter: `autumn.config.ts`, `autumn-js` credit checks, `atmn` CLI, plan gates, and metered AI usage. Use when changing billing, pricing, credits, plan access, refunds, or usage events.
- better-auth-best-practicesBetter Auth server/client setup: `auth.ts`, generated schema, DB adapters, sessions, cookies, env vars, and plugins. Use when mentioning Better Auth, betterauth, auth handlers, OAuth, email/password, or session configuration.
- better-auth-security-best-practicesBetter Auth security hardening: rate limits, secrets, CSRF, trusted origins, cookies, sessions, OAuth tokens, and audit logging. Use when reviewing auth security, brute-force protection, token handling, or deployment safety.
- change-proposalPresent proposed code changes visually before implementing. Use when: "show me options", "compare approaches", "what should we do", or when changes need before/after comparison.
- claude-code-consultUse this skill when the user asks to consult Claude, ask Claude Code, get another model's take, run a taste check, find cleaner options, or prepare a Claude prompt. Create a bounded second-opinion prompt or run a read-only Claude Code consult, then verify Claude's claims against local files.