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:- Client - Frontend (React, Vue, etc.)
- API Layer - HTTP endpoints (@api decorator)
- Model Layer - Business logic ⭐
- 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
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
- 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
Type Safety
Type Safety
TypeScript types are auto-generated based on Entity definitions, allowing errors to be caught at compile time.
Code Reuse
Code Reuse
Write common logic as Model methods and reuse across multiple APIs.
Testability
Testability
Models can be tested independently.
Separation of Concerns
Separation of Concerns
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