Skip to main content
Understand how Sonamu automatically generates type-safe client Services from backend APIs.

Auto-generated Service Overview

Type Safety

Synced with backend Compile-time validation

Namespace Based

Static functions Concise calls

TanStack Query

Auto-generated React Hooks Caching and revalidation

Subset Support

Only needed fields Performance optimization

Why Auto-generation?

Problem: Limitations of Manual API Clients

In traditional frontend development, you manually write client code to call backend APIs. Manual client example:
Problems with this approach:
  1. Lack of type safety: Overuse of any type, runtime errors occur
  2. Cannot track backend changes: Frontend doesn’t know when API changes
  3. Duplicate code: Similar code repeated for every API
  4. Prone to mistakes: URL typos, wrong parameters, etc.
  5. Hard to maintain: Need to modify all call sites when API changes

Solution: Benefits of Auto-generation

Sonamu analyzes the @api decorator from the backend to automatically generate type-safe clients. Auto-generated client example:
Benefits:
  1. ✨ Complete type safety: Backend types are directly reflected in frontend
  2. ✨ Immediate error detection: API changes detected at compile time
  3. ✨ Auto-completion: IDE automatically suggests API parameters and response types
  4. ✨ Namespace based: Clean structure, easy imports
  5. ✨ Single source of truth: Backend is the only source for API specs
Single Source of Truth is the principle where all information in the system derives from one source. In Sonamu, the @api decorator in the backend is the only API specification, and the frontend follows it.

Service Generation Process

Step 1: Backend API Definition

Define APIs with the @api decorator in the backend.
This API definition is the starting point for everything. Type information, parameters, and response format are all defined here.

Step 2: TypeScript AST Parsing

Sonamu uses the TypeScript compiler API to analyze the code. Analysis process:
Key concepts:
  • AST (Abstract Syntax Tree): Represents code as a tree structure
  • Type extraction: Obtains accurate type information from TypeScript’s type system
  • Metadata collection: Collects all information including decorator options, Guards, comments

Step 3: Namespace Service Generation

Based on collected information, Namespace-based Services are generated. Generated code (services.generated.ts):
Benefits of Namespace structure:
  • Simplicity: Simpler than classes (no new required)
  • Static methods: No state management needed
  • Tree-shaking: Unused functions excluded from bundle
  • Easy import: import { UserService } from "./services.generated"

Step 4: TanStack Query Hook Generation

Hooks that can be used directly in React are also auto-generated.
Benefits of TanStack Query integration:
  • Auto caching
  • Auto revalidation
  • Auto loading/error state management
  • Conditional fetching support
  • Optimistic updates support

Structure of Generated Services

fetch Utility Function

Common fetch function used by all Services.
Role of fetch function:
  • Wraps Axios calls: Passes options to Axios
  • Auto response extraction: Returns res.data directly
  • Error conversion: Axios error β†’ SonamuError
  • Zod issue handling: Type-safe handling of validation errors
AxiosRequestConfig parameters:

Subset System

Sonamu’s unique Subset system. What is Subset? A system that defines multiple variants (subsets) of an entity to query only needed fields.
Benefits of Subset:
  1. Performance: Query only needed fields to reduce network cost
  2. Type safety: Returns accurate type for each Subset
  3. Explicitness: Clearly express what data is needed in code
  4. Database optimization: Include only necessary columns in SELECT clause
Subset naming convention:
  • A: Basic fields (id, core info)
  • B: Intermediate fields (A + additional info)
  • C: All fields (all columns, including timestamps)

Type Safety in Practice

Compile-time Validation

When backend API changes, errors occur immediately at compile time. Backend change:
Frontend error:
This brings runtime errors to compile time to prevent bugs in advance.

IDE Auto-completion

Thanks to type information, IDE provides powerful auto-completion.

Development Workflow

Backend-First Development

Sonamu’s auto-generation encourages Backend-First development. Typical workflow: Benefits:
  • Clear contract between backend and frontend
  • Prevents bugs from type mismatch at source
  • Auto-generated API documentation (Service is the documentation)
  • Improved collaboration efficiency

Regeneration During Development

Services must be regenerated whenever API changes.
Cautions: - Never manually modify generated Service files (services.generated.ts) - If modifications needed, modify backend and regenerate - Team decides whether to add generated files to .gitignore - If added: Each person generates locally - If not added: Shared via Git (reduces build time)

Practical Usage Examples

Basic Usage

Usage in React (TanStack Query Hook)

Conditional Fetching

Advanced Features

qs.stringify Usage

Uses qs library to serialize query parameters for GET requests.
Why use qs:
  • Nested object support (filters[status]=active)
  • Array serialization support (ids[]=1&ids[]=2)
  • Matches backend’s parsing method

Error Handling

Handle SonamuError in a type-safe manner.

Query Options Reuse

Prefetching

Cautions

Cautions when using Services: 1. Never manually modify generated Service files (services.generated.ts) 2. Subset parameter required: Must specify subset like getUser("A", id) 3. It’s a Namespace so no new needed: Call UserService.getUser() directly 4. TanStack Query Hooks should only be called inside components 5. Use isSonamuError() type guard for error handling 6. Use qs.stringify() for complex object serialization

Next Steps

Using Services

How to use generated Services

TanStack Query Hook

Using in React

Creating APIs

@api decorator

Subset System

Subset system