Database Module in Akan.js

Database modules in Akan.js provide a structured approach to building domain-specific features with seamless integration between server and client.
Purpose of Database Modules

Domain Encapsulation

Encapsulate all domain-specific logic in a consistent structure

Full-Stack Integration

Seamless integration between MongoDB, NestJS server, and React client

Type Safety

Ensure type safety across entire stack with auto-generated types

Automated CRUD

Provide automatic CRUD operations through standardized patterns

File Structure and Location Conventions
A complete database module follows this structured organization:
libs/shared/lib/[module-name]/
├── [ModuleName].Template.tsx      // Form components
├── [ModuleName].Unit.tsx          // Card/list view components
├── [ModuleName].Util.tsx          // Utility components
├── [ModuleName].View.tsx          // Single item view components
├── [ModuleName].Zone.tsx          // Main zone layout
├── _server.ts                     // Module registration
├── [module-name].constant.ts      // Model definitions
├── [module-name].dictionary.ts    // Translations
├── [module-name].document.ts      // Database schema
├── [module-name].service.ts       // Business logic
├── [module-name].signal.ts        // API endpoints
├── [module-name].store.ts         // Client state
└── index.tsx                      // Module exports
Module Components Overview
ComponentPurpose
TemplateForm components for creating/editing data
UnitCard/list item components for summarized data
UtilSpecialized utility components (dashboard, insights)
ViewDetailed view components for full data models
ZoneLayout containers that organize multiple components
_server.tsModule registration file
constant.tsModel definitions and types
dictionary.tsInternationalization translations
document.tsMongoDB schema definitions
service.tsBusiness logic implementation
signal.tsAPI endpoint definitions
store.tsClient-side state management
index.tsxModule exports
Creating a Model Schema
Define your data model using the decorator pattern:
import { Field, Model } from "@akanjs/constant";
@Model.Object("UserObject")
export class UserObject {
  @Field.Prop(() => String, { validate: validate.email })
  email: string;
  
  @Field.Secret(() => String)
  password: string | null;
  
  @Field.Prop(() => [String], { enum: UserRole })
  roles: string[];
}
Implementing Database Schema
Create MongoDB schema with document methods and middleware:
import { Database } from "@akanjs/document";
@Database.Document(() => UserObject)
export class User extends UserObject {
  addRole(role: string) {
    if (!this.roles.includes(role)) 
      this.roles = [...this.roles, role];
    return this;
  }
}
Business Logic in Services
import { Service } from "@akanjs/service";
@Service("UserService")
export class UserService {
  async createUser(data: UserInput) {
    const existingUser = await this.findByEmail(data.email);
    if (existingUser) throw new Error("User exists");
    
    const user = await this.userModel.createUser(data);
    return user.set({ roles: ["user"] }).save();
  }
}
Defining API Endpoints
import { Signal, Mutation } from "@akanjs/signal";
@Signal()
export class UserSignal {
  @Mutation.Public()
  async signin(email: string, password: string) {
    return this.userService.signin(email, password);
  }
}
Client-Side State Management
import { StateCreator } from "zustand";
export const createUserStore: StateCreator<UserStore> = (set) => ({
  users: [],
  userForm: { email: "", password: null },
  
  setUsers: (users) => set({ users }),
  signin: async () => {
    const { userForm } = get();
    await fetch.user.signin(userForm.email, userForm.password);
  }
});
Best Practices

Naming Conventions

Use PascalCase for classes/components, camelCase for files

Security

Use @Field.Secret for sensitive data, apply permission guards

Code Organization

Keep business logic in services, use signals only for API

Performance

Use dataloader pattern, create proper indexes

Testing

Create signal tests for endpoints, mock services for unit tests

UI Components

Separate Template/Unit/View/Zone components

Real-time

Use GraphQL subscriptions and WebSockets

Data Flow in Database Modules
User Interaction
Store Action
Signal Call
Service Logic
Database Operation
UI Update
For detailed implementation examples, see our example projects repository
Released under the MIT License
Official Akan.js Consulting onAkansoft
Copyright © 2025 Akan.js. All rights reserved.
System managed bybassman