Use Cases Example
Project Structure
Section titled “Project Structure”use-cases-example/├── repositories/│ ├── IUserRepository.ts│ └── UserRepository.ts├── services/│ ├── IEmailService.ts│ ├── EmailService.ts│ ├── IApplicationService.ts│ └── ApplicationService.ts├── use-cases/│ ├── CreateUserUseCase.ts│ ├── GetUserUseCase.ts│ └── UserController.ts├── ioc.config.json└── container.gen.ts
Classes WITH Interfaces
Section titled “Classes WITH Interfaces”export interface IUserRepository { save(user: User): Promise<void>; findById(id: string): Promise<User | null>;}
export class UserRepository implements IUserRepository { async save(user: User): Promise<void> { // Implementation }
async findById(id: string): Promise<User | null> { // Implementation }}
Classes WITHOUT Interfaces
Section titled “Classes WITHOUT Interfaces”export class CreateUserUseCase { constructor( private userRepository: IUserRepository, private emailService: IEmailService ) {}
async execute(name: string, email: string): Promise<void> { const user = { id: Date.now().toString(), name, email };
await this.userRepository.save(user); await this.emailService.sendWelcomeEmail(user.email, user.name);
console.log(`User created: ${user.name} (${user.email})`); }}
Controller Using Use Cases
Section titled “Controller Using Use Cases”export class UserController { constructor( private createUserUseCase: CreateUserUseCase, private getUserUseCase: GetUserUseCase ) {}
async createUser(name: string, email: string): Promise<void> { await this.createUserUseCase.execute(name, email); }
async getUser(id: string): Promise<User | null> { return await this.getUserUseCase.execute(id); }}
Configuration
Section titled “Configuration”{ "source": ".", "output": "container.gen.ts", "interface": "I[A-Z].*", "exclude": [ "**/*.test.ts", "**/*.spec.ts" ], "verbose": true}
import { container } from './container.gen';
const userController = container.coreModule.UserController;
await userController.createUser('John Doe', 'john@example.com');
const user = await userController.getUser('123');
const createUserUseCase = container.coreModule.CreateUserUseCase;await createUserUseCase.execute('Jane Doe', 'jane@example.com');