Home Projects Portfolio Dashboard Export PDF Log in

Implementing Granular Status Updates in NestJS with TypeORM

In modern web platforms, the ability to dynamically manage the state of key entities is paramount for operational efficiency and user experience. For Acelerador 2.0, a platform focused on accelerating educational programs and managing mentors, this need was particularly acute. We recently rolled out a significant feature to introduce granular status update endpoints for critical components: milestones and edition mentors.

The Challenge

Prior to this development, managing the lifecycle and engagement status of milestones within projects and the active involvement of edition mentors often involved more manual or less integrated processes. This led to potential delays in reflecting real-time progress, inconsistencies in reporting, and a higher operational overhead. The core challenge was to provide a robust, secure, and programmatic way to reflect these changes instantly and accurately across the system.

The Solution

To address this, we leveraged NestJS to introduce dedicated API endpoints for updating the status of both milestones and edition mentors. The solution was built around a clean architecture, utilizing TypeORM for database interactions, adhering to the Repository Pattern, and relying heavily on NestJS's Dependency Injection system.

Each update flow involved:

  1. Controller: Receiving the API request, validating the input via Data Transfer Objects (DTOs).
  2. Service: Encapsulating the business logic, interacting with the repository.
  3. Repository: Handling the specific database operations using TypeORM.

Here's a conceptual look at how a status update might be handled for an entity:

// src/modules/milestones/milestones.controller.ts
import { Controller, Patch, Param, Body, HttpCode, HttpStatus, UseGuards } from '@nestjs/common';
import { MilestonesService } from './milestones.service';
import { UpdateMilestoneStatusDto } from './dto/update-milestone-status.dto';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard'; // Assuming JWT is used

@UseGuards(JwtAuthGuard)
@Controller('milestones')
export class MilestonesController {
  constructor(private readonly milestonesService: MilestonesService) {}

  @Patch(':id/status')
  @HttpCode(HttpStatus.OK)
  async updateStatus(
    @Param('id') id: string,
    @Body() updateStatusDto: UpdateMilestoneStatusDto,
  ) {
    return this.milestonesService.updateMilestoneStatus(id, updateStatusDto.status);
  }
}

// src/modules/milestones/milestones.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Milestone } from './entities/milestone.entity'; // Assuming this entity exists

@Injectable()
export class MilestonesService {
  constructor(
    @InjectRepository(Milestone)
    private milestonesRepository: Repository<Milestone>,
  ) {}

  async updateMilestoneStatus(id: string, newStatus: string): Promise<Milestone> {
    const milestone = await this.milestonesRepository.findOne({ where: { id } });
    if (!milestone) {
      throw new NotFoundException(`Milestone with ID ${id} not found.`);
    }
    milestone.status = newStatus;
    return this.milestonesRepository.save(milestone);
  }
}

// src/modules/milestones/dto/update-milestone-status.dto.ts
import { IsNotEmpty, IsString } from 'class-validator';

export class UpdateMilestoneStatusDto {
  @IsString()
  @IsNotEmpty()
  status: string; // e.g., 'pending', 'in-progress', 'completed'
}

Key Decisions

  1. Clear Endpoint Structure: Employing RESTful principles with specific PATCH endpoints like /milestones/:id/status and /mentors/:id/status for clarity and atomicity of updates.
  2. Robust Validation with DTOs: Leveraging class-validator and DTOs to ensure that all incoming status updates adhere to predefined schema and type constraints, preventing invalid states.
  3. Encapsulation of Business Logic: Services were designed to contain the specific business rules associated with status transitions, ensuring that the logic is centralized and testable, separated from controller concerns.
  4. Security: All update endpoints were secured using JWT-based authentication, ensuring only authorized personnel or system processes could initiate status changes.

Results

The implementation of these dedicated status update endpoints significantly enhanced the Acelerador 2.0 platform's agility and data integrity.

  • Real-time Visibility: Stakeholders now have immediate and accurate insight into project milestones and mentor availability.
  • Reduced Manual Effort: Automation of status updates minimizes human error and reduces operational overhead.
  • Improved System Integration: Provides a clean API surface for other microservices or frontend applications to interact with, facilitating seamless workflows.

Lessons Learned

Designing APIs for granular, atomic updates to key entity attributes, rather than relying on full entity updates, leads to more robust, secure, and efficient systems. It allows for clearer authorization rules and minimizes the risk of unintended side effects, proving invaluable in complex domain models like Acelerador 2.0.


Generated with Gitvlg.com

Implementing Granular Status Updates in NestJS with TypeORM
Daniela Homobono

Daniela Homobono

Author

Share: