Agent skill
query-layer
Query layer patterns for consuming services with TanStack Query, error transformation, and runtime dependency injection. Use when the user mentions createQuery, createMutation, TanStack Query, or when implementing queries/mutations, transforming errors for UI, or adding reactive data management.
Install this agent skill to your Project
npx add-skill https://github.com/EpicenterHQ/epicenter/tree/main/.agents/skills/query-layer
Metadata
Additional technical details for this skill
- author
- epicenter
- version
- 2.0
SKILL.md
Query Layer Patterns
Reference Repositories
- TanStack Query — Async state management for data fetching
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-layerfor the service layer these queries consume. Seesveltefor Svelte-specific TanStack Query patterns.
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
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:
<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:
// In an event handler or workflow
async function handleTransform(recordingId: string, transformation: Transformation) {
const { error } = await rpc.transformer.transformRecording.execute({
recordingId,
transformation,
});
if (error) {
notify.error.execute(error);
return;
}
notify.success.execute({ title: 'Transformation complete' });
}
// In a sequential workflow
async function stopAndTranscribe(toastId: string) {
const { data: blobData, error: stopError } =
await rpc.recorder.stopRecording.execute({ toastId });
if (stopError) {
notify.error.execute(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
- Always transform errors at query boundary - Never return raw service errors
- Use
.options(no parentheses) - It's a static object, wrap in accessor for Svelte - Never double-wrap errors - Each error is wrapped exactly once
- Services are pure, queries inject settings - Services take explicit params
- Use
.execute()in.tsfiles -createMutationrequires component context - 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
-
If working with runtime dependency injection and service selection, read references/runtime-dependency-injection.md
-
If working with cache management, query definitions, RPC namespace, or notify coordination, read references/advanced-query-patterns.md
-
See
apps/whispering/src/lib/query/README.mdfor detailed architecture -
See the
services-layerskill for how services are implemented -
See the
error-handlingskill for trySync/tryAsync patterns
Recommended Agent Skills
Expand your agent's capabilities with these related and highly-rated skills.
svelte
Svelte 5 patterns including runes ($state, $derived, $props), TanStack Query, SvelteMap reactive state, shadcn-svelte components, and component composition. Use when the user mentions .svelte files, Svelte components, or when using TanStack Query, fromTable/fromKv, or shadcn-svelte UI.
autumn
Integrate Autumn billing—define features/plans in autumn.config.ts, use autumn-js SDK for credit checks/tracking, manage the atmn CLI for push/pull. Use when working on billing, pricing, credits, plan gating, or metered usage.
handoff-prompt
Draft a self-contained implementation prompt that an agent can execute with zero prior context. Use when the user says "draft a prompt", "write a handoff", "make a prompt I can copy-paste", "create a delegation brief", or wants to hand off a task to another agent, tool, or conversation.
typebox
TypeBox and TypeMap patterns for runtime schema validation and JSON Schema generation. Use when the user mentions TypeBox, TypeMap, Standard Schema, or when working with runtime type validation, JSON Schema, or schema-based validation.
factory-function-composition
Apply factory function patterns to compose clients and services with proper separation of concerns. Use when creating functions that depend on external clients, wrapping resources with domain-specific methods, or refactoring code that mixes client/service/method options together.
progress-summary
This skill should be used when the user asks questions like "can you summarize", "what happened", "what did we do", "what's the situation", "where are we at", "explain what's going on", "give me an overview", "what's been done", "tell me about this", "walk me through what happened", or any question asking to understand the current state of work or changes. Provides conversational, PR-style summaries with visual diagrams.
Didn't find tool you were looking for?