query-layer

0
0
Source

Query layer patterns for consuming services with TanStack Query, error transformation, and runtime dependency injection. Use when implementing queries/mutations, transforming service errors for UI, or adding reactive data management.

Install

mkdir -p .claude/skills/query-layer && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4567" && unzip -o skill.zip -d .claude/skills/query-layer && rm skill.zip

Installs to .claude/skills/query-layer

About this skill

Query Layer Patterns

Reference Repositories

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.

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/createMutationUse .execute()/.fetch()
Component data displayEvent handlers
Loading spinners neededSequential workflows
Auto-refetch wantedOne-time operations
Reactive state neededOutside component context
Cache synchronizationPerformance-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 .execute() 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:

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

294790

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

213415

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

213296

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

222234

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

174201

rust-coding-skill

UtakataKyosui

Guides Claude in writing idiomatic, efficient, well-structured Rust code using proper data modeling, traits, impl organization, macros, and build-speed best practices.

166173

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.