Skip to main content

Module Structure

A module is the basic building block of the Zochil API. Each module represents a specific business domain and contains two essential files: routes.ts and service.ts.

Module Pattern

Routes (routes.ts)

The routes.ts file creates and exports an Express Router. It handles HTTP route definitions, request validation, and middleware integration.

Example Route File

Route Responsibilities

  • Express Router: Create and configure HTTP routes
  • Validation: Input validation with express-validator
  • Authentication: Apply authentication middleware
  • Response Handling: Use service.handleOk() for consistent responses
  • Dependency Injection: Receive DBConnection from parent router

Services (service.ts)

The service.ts file contains the business logic and data access layer. All service classes extend the base APIService class.

Example Service File

Service Responsibilities

  • Business Logic: Core domain logic and data processing
  • Database Access: Query database using Knex.js patterns
  • Multi-tenancy: Automatic filtering by shop_id/merchant_id
  • Error Handling: Use CustomError for structured exceptions
  • Event Publishing: Publish domain events via this.publishEvent()

Base Classes

APIService Base Class

Located at ./api/@core/base/service.ts, provides common functionality:

Merchant Service Composition

For merchant-related functionality, use the MerchantService as a composed property:

Database Connection

All modules receive a DBConnection interface containing:

Database Access Patterns

  • Knex Queries: Use this.connector.db(tableName) for database access
  • Multi-tenancy: Always filter by shop_id or merchant_id
  • Transactions: Use Knex transactions for complex operations
  • Connection Pooling: Automatic connection management

Authentication & Middleware

Request Context

Authentication middlewares populate request objects with user context:

Authentication Middleware

Authorization

Role-based access control using user context: