Skip to main content
Model is a core layer of Sonamu that handles business logic and data access. Based on Entity definitions, it provides database queries, API endpoints, and type-safe data processing.

Role of Model

Data Access

Database CRUD operations Type-safe queries through Puri query builder

Business Logic

Implementing domain rules Data validation, transformation, calculation

API Endpoints

Automatic HTTP API generation REST API provided via @api decorator

Type Safety

Compile-time type checking Auto-generated types based on Entity

Position in Sonamu Architecture

Layer Structure:
  1. Client - Frontend (React, Vue, etc.)
  2. API Layer - HTTP endpoints (@api decorator)
  3. Model Layer - Business logic ⭐
  4. Database - PostgreSQL
Model is the business logic layer between API Layer and Database. All data access and business rules are handled in Model.

Model Class Structure

Basic Structure

user.model.ts

Generic Type Parameters

These generic types are automatically generated in sonamu.generated.ts and sonamu.generated.sso.ts, so you don’t need to write them manually.

Model vs Entity vs Types

Let’s clarify commonly confused concepts in Sonamu: Examples:

Features Provided by Model

1. Type-Safe Data Access

2. Subset-Based Queries

Subsets reduce network traffic and improve performance by selecting only the fields needed for API responses.

3. Automatic API Generation

What gets auto-generated:
  • HTTP endpoint: GET /user/findById?id=1
  • TypeScript client code
  • TanStack Query hooks
  • API documentation

4. Transaction Management

5. Data Validation and Transformation

Model Writing Patterns

CRUD Methods

A typical Model provides the following CRUD methods:

Domain-Specific Methods

You can add methods specialized for business domains:

BaseModel Methods

BaseModelClass provides the following utility methods:
Learn More - BaseModel Methods - Detailed method guide

Advantages of Model

TypeScript types are auto-generated based on Entity definitions, allowing errors to be caught at compile time.
Write common logic as Model methods and reuse across multiple APIs.
Models can be tested independently.
Clearly separates business logic (Model) from HTTP handling (Controller/API).
  • Model: Data processing, business rules
  • API: HTTP request/response, authentication, authorization

Next Steps

After understanding the basic concepts of Model, learn the following topics:

Creating Models

Creating Models and using Scaffold

API Decorator

Creating API endpoints with @api decorator

Business Logic

Business logic writing patterns and examples

BaseModel Methods

Learn all methods provided by BaseModel