Home Projects Portfolio Dashboard Export PDF Log in

Building Robust API Endpoints for Active Edition Management in NestJS

Project Context

In the Edu568/Acelerador-2.0 project, a key focus is on managing various entities within an accelerator program. This initiative involves enhancing the system with new API endpoints to handle participants, mentors, and organizations specifically for an "active edition." The goal is to provide a comprehensive set of interfaces for managing the lifecycle and data associated with these crucial roles during an ongoing program iteration.

The Need for Active Edition Management

Imagine an accelerator program with multiple editions running throughout the year. Each edition has its own set of participants, mentors, and partner organizations. To effectively manage the current, or "active," edition, the application requires dedicated endpoints for listing, creating, updating, and deleting these entities. This separation ensures that operations on the active edition do not inadvertently affect past or future editions, maintaining data integrity and clarity for administrators.

Architectural Approach: NestJS and Hexagonal Principles

To build these endpoints, we leverage NestJS, a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. Our architecture follows Hexagonal Architecture principles, ensuring a clear separation of concerns. This means that our core business logic remains independent of external frameworks (like NestJS controllers) or data access layers (TypeORM). Dependency Injection is heavily used to manage component relationships, making the system modular and testable. The Repository Pattern is instrumental in abstracting data storage details, allowing our application services to interact with a consistent interface regardless of the underlying database technology (in this case, TypeORM).

Implementing the Participant Module

Let's walk through a simplified example for a Participant entity, illustrating how these principles are applied.

Controller: API Gateway

The controller acts as the entry point for incoming HTTP requests. It handles routing, request validation, and delegates business logic to the service layer. It should be lean and primarily concerned with HTTP concerns.

import { Controller, Get, Post, Body, Param, Put, Delete } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { ParticipantService } from './participant.service';
import { CreateParticipantDto, UpdateParticipantDto } from './dto/participant.dto';
import { Participant } from './entities/participant.entity';

@ApiTags('Participants')
@Controller('active-edition/participants')
export class ParticipantController {
  constructor(private readonly participantService: ParticipantService) {}

  @Post()
  @ApiOperation({ summary: 'Create a new participant for the active edition' })
  @ApiResponse({ status: 201, description: 'Participant created successfully.' })
  async create(@Body() createParticipantDto: CreateParticipantDto): Promise<Participant> {
    return this.participantService.create(createParticipantDto);
  }

  @Get()
  @ApiOperation({ summary: 'Retrieve all participants for the active edition' })
  @ApiResponse({ status: 200, description: 'List of participants.' })
  async findAll(): Promise<Participant[]> {
    return this.participantService.findAll();
  }

  @Get(':id')
  @ApiOperation({ summary: 'Retrieve a single participant by ID for the active edition' })
  @ApiResponse({ status: 200, description: 'Participant details.' })
  @ApiResponse({ status: 404, description: 'Participant not found.' })
  async findOne(@Param('id') id: string): Promise<Participant> {
    return this.participantService.findOne(id);
  }

  @Put(':id')
  @ApiOperation({ summary: 'Update an existing participant for the active edition' })
  @ApiResponse({ status: 200, description: 'Participant updated successfully.' })
  async update(@Param('id') id: string, @Body() updateParticipantDto: UpdateParticipantDto): Promise<Participant> {
    return this.participantService.update(id, updateParticipantDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Delete a participant from the active edition' })
  @ApiResponse({ status: 204, description: 'Participant deleted successfully.' })
  async remove(@Param('id') id: string): Promise<void> {
    await this.participantService.remove(id);
  }
}

Service: Business Logic

The service layer encapsulates the core business rules and orchestrates interactions with the data layer (repositories) and other services. It's crucial for maintaining consistency and enforcing domain-specific logic.

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Participant } from './entities/participant.entity';
import { CreateParticipantDto, UpdateParticipantDto } from './dto/participant.dto';

@Injectable()
export class ParticipantService {
  constructor(
    @InjectRepository(Participant)
    private readonly participantRepository: Repository<Participant>,
  ) {}

  async create(createParticipantDto: CreateParticipantDto): Promise<Participant> {
    const newParticipant = this.participantRepository.create(createParticipantDto);
    return this.participantRepository.save(newParticipant);
  }

  async findAll(): Promise<Participant[]> {
    return this.participantRepository.find();
  }

  async findOne(id: string): Promise<Participant> {
    const participant = await this.participantRepository.findOne({ where: { id } });
    if (!participant) {
      throw new NotFoundException(`Participant with ID ${id} not found`);
    }
    return participant;
  }

  async update(id: string, updateParticipantDto: UpdateParticipantDto): Promise<Participant> {
    const participant = await this.findOne(id); // Reuses findOne for validation
    this.participantRepository.merge(participant, updateParticipantDto);
    return this.participantRepository.save(participant);
  }

  async remove(id: string): Promise<void> {
    const result = await this.participantRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`Participant with ID ${id} not found`);
    }
  }
}

Repository: Data Abstraction

While NestJS and TypeORM provide @InjectRepository, in a pure Hexagonal Architecture, you might define an interface (port) for IParticipantRepository in the domain layer and implement it (adapter) using TypeORM. For simplicity with NestJS, InjectRepository provides a direct way to use TypeORM's Repository class, which inherently follows the pattern of abstracting database operations.

// entities/participant.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class Participant {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;

  @Column({ default: true })
  isActive: boolean;
}

Benefits and Conclusion

By implementing these dedicated API endpoints with a structured approach, the Acelerador-2.0 project gains several advantages:

  • Clear Separation: Business logic is isolated from infrastructure concerns.
  • Maintainability: Changes in data storage or presentation layers have minimal impact on core logic.
  • Testability: Each layer can be tested independently.
  • Scalability: The modular design supports easier expansion to other entities and features.
  • API Documentation: Integration with Swagger (using @ApiTags, @ApiOperation, etc.) ensures robust and automatically generated API documentation, simplifying consumption for frontend developers.

This robust setup, leveraging NestJS, TypeORM, and architectural patterns, allows for efficient and reliable management of program entities within an active edition.

Next Steps

Consider adding JWT guards for authentication and authorization to secure these endpoints, ensuring only authorized personnel can perform operations. Additionally, implement robust validation pipelines using NestJS's ValidationPipe with class-validator to ensure incoming data conforms to expected schemas.


Generated with Gitvlg.com

Building Robust API Endpoints for Active Edition Management in NestJS
Daniela Homobono

Daniela Homobono

Author

Share: