Model Creation Process
1
Define Entity
First, you need to define an Entity.
user.entity.json
2
Auto Type Generation
Type files are automatically generated when you save the Entity.Generated files:
user.types.ts- TypeScript types and Zod schemassonamu.generated.ts- Base schemas and Enumssonamu.generated.sso.ts- Subset query functions
3
Generate Model Scaffold
Use Sonamu CLI to generate a Model template.Or generate from the Scaffolding tab in Sonamu UI.
4
Customize Model
Add business logic to the generated Model.
Creating Models with Scaffold
Using CLI
Using Sonamu UI
1
Open Scaffolding Tab
Click the Scaffolding tab in Sonamu UI (
http://localhost:34900/sonamu-ui).2
Select Model Template
Select the “Model” template and specify the Entity.
3
Configure Options
- Default Search Field: Default search field (e.g.,
email) - Default Order By: Default sorting (e.g.,
id-desc) - Overwrite: Whether to overwrite existing files
4
Execute Generation
Click the “Generate” button to create the Model file.
📸 Needed: Scaffolding tab in Sonamu UI - Model generation screen
Generated Model Structure
Basic structure of a Model generated by Scaffold:user.model.ts
Generated Methods Explanation
Default methods generated by Scaffold:1. findById
Retrieves a single record by ID.- Receives Subset as parameter to query only needed fields
- Throws
NotFoundExceptionif record doesn’t exist - Creates HTTP endpoint with
@apidecorator
2. findOne
Retrieves the first record matching conditions.- Returns
nullif record doesn’t exist (no exception thrown) - Internally calls
findManywithnum: 1, page: 1
3. findMany
Retrieves multiple records based on conditions.- Supports pagination (
num,page) - Search/filtering (
search,keyword) - Sorting (
orderBy) - Returns
{ rows, total }withListResulttype
4. save
Creates or updates records.- Uses Upsert Builder (Insert or Update)
- Processes multiple records at once with array
- Executes wrapped in transaction
- Returns array of created/updated IDs
5. del
Deletes records.- Receives multiple IDs as array
- Executes in transaction
- Only admins can delete with
guards: ["admin"] - Returns number of deleted records
Creating Models Manually
You can also write manually without using Scaffold.Minimum Structure
Naming Conventions
Model File Location
Model files are located in the same directory as the Entity:Writing Types File
Define parameter types to use with Model:user.types.ts
{Entity}ListParams: For list queries{Entity}SaveParams: For create/update{Entity}{Action}Params: For specific actions (e.g.,LoginParams)
Verifying Model Registration
Verify that the generated Model loads properly:api/src/application/sonamu.generated.ts
Next Steps
After creating a Model, learn the following topics:API Decorator
Creating HTTP APIs with @api decorator
Business Logic
Learning business logic writing patterns
Puri Query Builder
Writing type-safe queries
Testing
Writing Model tests