Building a Team Project View Endpoint in NestJS
In the Acelerador-2.0 project, focused on accelerating project development, a key enhancement was recently implemented: a dedicated endpoint to retrieve and display a specific project associated with a team. This feature is crucial for enabling team members and managers to quickly access and review project details relevant to their team's activities.
Developing such an endpoint, especially within a robust framework like NestJS, provides an excellent opportunity to reinforce architectural best practices, leveraging concepts like the Repository Pattern, Dependency Injection, and a clear separation of concerns.
Designing the Endpoint
The goal was to create an API endpoint that allows retrieval of a single project by its ID, but only if that project belongs to a specified team. This ensures data integrity and proper access control. The chosen path, GET /team/:teamId/project/:projectId, clearly communicates the hierarchical relationship.
Controller and Service Interaction
In NestJS, this typically involves a Controller handling the incoming HTTP request, and a Service containing the business logic. The Controller extracts teamId and projectId from the URL parameters, then delegates the retrieval logic to the Service.
// src/modules/team/team.controller.ts
import { Controller, Get, Param, ParseUUIDPipe } from '@nestjs/common';
import { TeamService } from './team.service';
@Controller('team')
export class TeamController {
constructor(private readonly teamService: TeamService) {}
@Get(':teamId/project/:projectId')
async getTeamProject(
@Param('teamId', ParseUUIDPipe) teamId: string,
@Param('projectId', ParseUUIDPipe) projectId: string,
) {
return this.teamService.findProjectInTeam(teamId, projectId);
}
}
// src/modules/team/team.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { ProjectRepository } from '../project/project.repository';
@Injectable()
export class TeamService {
constructor(private readonly projectRepository: ProjectRepository) {}
async findProjectInTeam(teamId: string, projectId: string) {
const project = await this.projectRepository.findByTeamAndProject(
teamId,
projectId
);
if (!project) {
throw new NotFoundException('Project not found in specified team.');
}
return project;
}
}
The ParseUUIDPipe is a useful NestJS feature for automatically validating that the provided teamId and projectId are valid UUIDs, enhancing input validation right at the entry point.
Leveraging the Repository Pattern with TypeORM
Within the TeamService, the actual data retrieval is handled by a ProjectRepository. This adheres to the Repository Pattern, abstracting database operations and promoting a cleaner architecture. TypeORM is an excellent choice for implementing this pattern in TypeScript applications.
// src/modules/project/project.repository.ts
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { ProjectEntity } from './project.entity'; // Assuming ProjectEntity exists
@Injectable()
export class ProjectRepository {
constructor(
@InjectRepository(ProjectEntity)
private readonly projectOrmRepository: Repository<ProjectEntity>,
) {}
async findByTeamAndProject(teamId: string, projectId: string): Promise<ProjectEntity | undefined> {
return this.projectOrmRepository.findOne({
where: { id: projectId, teamId: teamId }, // Assuming 'teamId' is a field in ProjectEntity
});
}
}
This ProjectRepository isolates the TypeORM-specific logic, making the TeamService agnostic to the underlying database implementation. If the data source changes (e.g., from a relational database to a NoSQL database), only the repository implementation needs to be updated, not the services that consume it.
Actionable Takeaway
When building new API features, especially those involving nested resources, always prioritize a clear separation of concerns. Utilize the Repository Pattern to abstract data access, and leverage your framework's features (like NestJS pipes) for robust validation. This approach leads to more maintainable, testable, and scalable codebases.
Generated with Gitvlg.com