services-layer
Service layer patterns with createTaggedError, namespace exports, and Result types. Use when creating new services, defining domain-specific errors, or understanding the service architecture.
Install
mkdir -p .claude/skills/services-layer && curl -L -o skill.zip "https://mcp.directory/api/skills/download/2304" && unzip -o skill.zip -d .claude/skills/services-layer && rm skill.zipInstalls to .claude/skills/services-layer
About this skill
Services Layer Patterns
This skill documents how to implement services in the Whispering architecture. Services are pure, isolated business logic with no UI dependencies that return Result<T, E> types for error handling.
Related Skills: See
error-handlingfor trySync/tryAsync patterns. Seedefine-errorsfor error variant factories. Seequery-layerfor consuming services with TanStack Query.
When to Apply This Skill
Use this pattern when you need to:
- Create a new service with domain-specific error handling
- Add error types with structured context (like HTTP status codes)
- Understand how services are organized and exported
- Implement platform-specific service variants (desktop vs web)
Core Architecture
Services follow a three-layer architecture: Service → Query → UI
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
│ UI │ --> │ RPC/Query │ --> │ Services │
│ Components │ │ Layer │ │ (Pure) │
└─────────────┘ └─────────────┘ └──────────────┘
Services are:
- Pure: Accept explicit parameters, no hidden dependencies
- Isolated: No knowledge of UI state, settings, or reactive stores
- Testable: Easy to unit test with mock parameters
- Consistent: All return
Result<T, E>types for uniform error handling
Creating Errors with defineErrors
Every service defines domain-specific errors using defineErrors from wellcrafted. Errors are grouped into a namespace object where each key becomes a variant.
import { defineErrors, type InferError, type InferErrors, extractErrorMessage } from 'wellcrafted/error';
import { Err, Ok, type Result, tryAsync, trySync } from 'wellcrafted/result';
// Namespace-style error definition — name describes the domain
const CompletionError = defineErrors({
ConnectionFailed: ({ cause }: { cause: unknown }) => ({
message: `Connection failed: ${extractErrorMessage(cause)}`,
cause,
}),
EmptyResponse: ({ providerLabel }: { providerLabel: string }) => ({
message: `${providerLabel} API returned an empty response`,
providerLabel,
}),
MissingParam: ({ param }: { param: string }) => ({
message: `${param} is required`,
param,
}),
});
// Type derivation — shadow the const with a type of the same name
type CompletionError = InferErrors<typeof CompletionError>;
type ConnectionFailedError = InferError<typeof CompletionError.ConnectionFailed>;
// Call sites — each variant returns Err<...> directly
return CompletionError.ConnectionFailed({ cause: error });
return CompletionError.EmptyResponse({ providerLabel: 'OpenAI' });
return CompletionError.MissingParam({ param: 'apiKey' });
How defineErrors Works
defineErrors({ ... }) takes an object of factory functions and returns a namespace object. Each key becomes a variant:
nameis auto-stamped from the key (e.g., keyNotFound→error.name === 'NotFound')- The factory function IS the message generator — it returns
{ message, ...fields } - Each variant returns
Err<...>directly — no separateFooErrconstructor needed - Types use
InferError/InferErrors— notReturnType
// No-input variant (static message)
const RecorderError = defineErrors({
Busy: () => ({
message: 'A recording is already in progress',
}),
});
// Usage — no arguments needed
return RecorderError.Busy();
// Variant with derived fields — constructor extracts from raw input
const HttpError = defineErrors({
Response: ({ response, body }: { response: { status: number }; body: unknown }) => ({
message: `HTTP ${response.status}: ${extractErrorMessage(body)}`,
status: response.status,
body,
}),
});
// Usage — pass raw objects, constructor derives fields
return HttpError.Response({ response, body: await response.json() });
// error.message → "HTTP 401: Unauthorized"
// error.status → 401 (derived from response, flat on the object)
// error.name → "Response"
Error Type Examples from the Codebase
// Static message, no input needed
const RecorderError = defineErrors({
Busy: () => ({
message: 'A recording is already in progress',
}),
});
RecorderError.Busy()
// Multiple related errors in a single namespace
const HttpError = defineErrors({
Connection: ({ cause }: { cause: unknown }) => ({
message: `Failed to connect to the server: ${extractErrorMessage(cause)}`,
cause,
}),
Response: ({ response, body }: { response: { status: number }; body: unknown }) => ({
message: `HTTP ${response.status}: ${extractErrorMessage(body)}`,
status: response.status,
body,
}),
Parse: ({ cause }: { cause: unknown }) => ({
message: `Failed to parse response body: ${extractErrorMessage(cause)}`,
cause,
}),
});
// Union type for the whole namespace
type HttpError = InferErrors<typeof HttpError>;
// Individual variant type
type ConnectionError = InferError<typeof HttpError.Connection>;
Key Rules
- Services never import settings - Pass configuration as parameters
- Services never import UI code - No toasts, no notifications, no WhisperingError
- Always return Result types - Never throw errors
- Use trySync/tryAsync - See the error-handling skill for details
- Export factory + Live instance - Factory for testing, Live for production
- Use defineErrors namespaces - Group related errors under a single namespace
- Derive types with InferError/InferErrors - Not
ReturnType - Variant names describe the failure mode - Never use generic names like
Service,Error, orFailed. The namespace provides domain context (RecorderError), so the variant must say what went wrong (AlreadyRecording,InitFailed,StreamAcquisition).RecorderError.Serviceis meaningless —RecorderError.AlreadyRecordingtells you exactly what happened. - Split discriminated union inputs - Each variant gets its own name and shape. If the constructor branches on its inputs (if/switch/ternary) to decide the message, each branch should be its own variant
- Transform cause in the constructor, not the call site - Accept
cause: unknownand callextractErrorMessage(cause)inside the factory's message template. Call sites pass the raw error:{ cause: error }. This centralizes message extraction where the message is composed and keeps call sites clean.
References
Load these on demand based on what you're working on:
-
If working with error variant anti-patterns (discriminated union inputs, branching constructors), read references/error-anti-patterns.md
-
If working with service implementation details (factory patterns, recorder service examples), read references/service-implementation-pattern.md
-
If working with service organization and platform variants (namespace exports, desktop vs web services), read references/service-organization-platforms.md
-
If working with error message authoring (user-friendly/actionable message design), read references/error-message-best-practices.md
-
See
apps/whispering/src/lib/services/README.mdfor architecture details -
See the
query-layerskill for how services are consumed -
See the
error-handlingskill for trySync/tryAsync patterns
More by EpicenterHQ
View all skills by EpicenterHQ →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.
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."
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.
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.
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.
pdf-to-markdown
aliceisjustplaying
Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.
Related MCP Servers
Browse all serversNCP (MCP Orchestrator) unifies MCP servers into one gateway with RAG-powered discovery and smart routing for GitHub, Sla
Search and discover MCP servers with the official MCP Registry — browse an up-to-date MCP server list to find MCP server
Supercharge browser tasks with Browser MCP—AI-driven, local browser automation for powerful, private testing. Inspired b
Find official MCP servers for Google Maps. Explore resources to build, integrate, and extend apps with Google directions
Explore official Google BigQuery MCP servers. Find resources and examples to build context-aware apps in Google's ecosys
Explore MCP servers for Google Compute Engine. Integrate model context protocol solutions to streamline GCE app developm
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.