Relevant source files
The following files were used as context for generating this wiki page:
- apps/api/src/comments/comments.service.ts
- apps/api/src/comments/comments.controller.ts
- apps/api/src/comments/dto/comment-responses.dto.ts
- apps/api/src/comments/comments.module.ts
- apps/api/src/comments/dto/update-comment.dto.ts
- apps/api/src/comments/dto/create-comment.dto.ts
- apps/api/src/comments/dto/delete-comment.dto.ts
The Comments System provides a robust API for managing comments associated with various entities within the application, such as tasks, policies, vendors, and risks. It supports creating, retrieving, updating, and deleting comments, including handling file attachments and user mentions. The system is designed to ensure data consistency through transactions and integrates with an attachment service for file management and a notification service for user mentions.
Architecture Overview
The Comments System is implemented as a NestJS module, following a standard Controller-Service pattern.
CommentsController: Handles incoming HTTP requests, validates input, and delegates business logic to theCommentsService. It defines the API endpoints for comment operations.CommentsService: Contains the core business logic for managing comments, interacting with the database,AttachmentsService, andCommentMentionNotifierService. It also includes access validation for entities.- DTOs (Data Transfer Objects): Define the structure for request payloads and API responses, ensuring clear data contracts.
CommentsModule: Orchestrates the components, declares providers and controllers, and manages dependencies.
The system leverages HybridAuthGuard for flexible authentication (JWT or API Key) and uses AuthContext to determine the authenticated user and organization.
Sources: apps/api/src/comments/comments.controller.ts, apps/api/src/comments/comments.service.ts, apps/api/src/comments/comments.module.ts
Data Transfer Objects (DTOs)
The Comments System uses several DTOs to structure data for requests and responses.
Request DTOs
CreateCommentDto: Used when creating a new comment.content: The text content of the comment (max 2000 characters).entityId: The ID of the entity the comment belongs to.entityType: The type of entity (task,policy,vendor,risk).contextUrl?: Optional URL for deep-linking in notifications.attachments?: An array ofUploadAttachmentDtofor files to be attached.userId?: Required for API key authentication to specify the author.
UpdateCommentDto: Used when updating an existing comment.content: The new text content of the comment (max 2000 characters).contextUrl?: Optional updated URL for deep-linking.userId?: Required for API key authentication to specify the author.
DeleteCommentDto: Used when deleting a comment.userId?: Required for API key authentication to specify the user performing the deletion.
Sources: apps/api/src/comments/dto/create-comment.dto.ts, apps/api/src/comments/dto/update-comment.dto.ts, apps/api/src/comments/dto/delete-comment.dto.ts
Response DTOs
The primary response DTO is CommentResponseDto, which includes nested DTOs for author information and attachment metadata.
CommentResponseDto: Represents a single comment returned by the API.id: Unique identifier for the comment.content: The comment's text content.author: AnAuthorResponseDtoobject containing details about the comment's author.attachments: An array ofAttachmentMetadataDtoobjects, providing metadata about attached files (without download URLs, which are generated on-demand).createdAt: Timestamp of when the comment was created.
AuthorResponseDto: Details about the user who authored the comment.id,name,email,image,deactivated.
AttachmentMetadataDto: Basic metadata for an attachment associated with a comment.id,name,type,createdAt.
AttachmentResponseDto: Similar toAttachmentMetadataDtobut includes adownloadUrlandsize. This is used internally by the service when handling attachments, butAttachmentMetadataDtois returned inCommentResponseDto.
Sources: apps/api/src/comments/dto/comment-responses.dto.ts
API Endpoints
The CommentsController exposes the following REST API endpoints:
| Method | Path | Description | Request Body | Response Type | Authentication |
|---|---|---|---|---|---|
GET | /comments | Retrieve all comments for a specific entity. | Query: entityId, entityType | CommentResponseDto[] | HybridAuthGuard |
POST | /comments | Create a new comment on an entity with optional attachments. | CreateCommentDto | CommentResponseDto | HybridAuthGuard |
PUT | /comments/:commentId | Update the content of an existing comment (author only). | UpdateCommentDto | CommentResponseDto | HybridAuthGuard |
DELETE | /comments/:commentId | Delete a comment and all its attachments (author only). | DeleteCommentDto | { success: boolean, deletedCommentId: string, message: string } | HybridAuthGuard |
All endpoints require an X-Organization-Id header for session authentication, which is optional for API key authentication.
Sources: apps/api/src/comments/comments.controller.ts
Core Logic: CommentsService
The CommentsService encapsulates the business logic for comment management.
Entity Access Validation
Before performing any comment operation, the service validates that the target entity exists within the specified organization and that the user has access. This is handled by the validateEntityAccess method.
The supported CommentEntityType values are:
task: Checks forTaskItemfirst, thenTask.policy: Checks forPolicy.vendor: Checks forVendor. Includes logging if a vendor exists in a different organization.risk: Checks forRisk.
Sources: apps/api/src/comments/comments.service.ts
Creating a Comment
The createComment method handles the creation of new comments, including optional attachments and user mention notifications.
Validate Entity Access
The system first calls
validateEntityAccessto ensure theentityIdandentityTypeare valid and accessible within theorganizationId.Verify Member
It retrieves the
Memberrecord for theuserIdwithin theorganizationIdto confirm the user is an active member.Create Comment and Attachments in Transaction
A database transaction is used to ensure atomicity.
- The comment record is created in the database.
- If
createCommentDto.attachmentsare provided, each attachment is uploaded viaAttachmentsService.uploadAttachmentand associated with the new comment.
Notify Mentioned Users
After the comment is successfully created, the
extractMentionedUserIdsutility parses the comment content for user mentions. If any users are mentioned,CommentMentionNotifierService.notifyMentionedUsersis called asynchronously to send notifications.
Sources: apps/api/src/comments/comments.service.ts
Retrieving Comments
The getComments method fetches all comments for a given entity.
- It first validates entity access using
validateEntityAccess. - It queries the database for comments matching the
organizationId,entityId, andentityType, ordering them by creation date (descending). - For each comment, it retrieves attachment metadata using
AttachmentsService.getAttachmentMetadata. - The results are mapped to
CommentResponseDtoobjects, including author details and attachment metadata.
Sources: apps/api/src/comments/comments.service.ts
Updating a Comment
The updateComment method allows modifying the content of an existing comment.
- It retrieves the existing comment and verifies that the
userIdis the author of the comment. - The comment's
contentis updated in the database. - Existing attachments are retrieved using
AttachmentsService.getAttachments. - It compares the newly mentioned users with previously mentioned users in the comment content. Only newly mentioned users are notified via
CommentMentionNotifierService.
Sources: apps/api/src/comments/comments.service.ts
Deleting a Comment
The deleteComment method removes a comment and its associated attachments.
- It retrieves the existing comment and verifies that the
userIdis the author of the comment. - A database transaction is initiated.
- All attachments linked to the comment are retrieved.
- Each attachment is deleted from storage via
AttachmentsService.deleteAttachment. - Finally, the comment record is deleted from the database.
Sources: apps/api/src/comments/comments.service.ts
Mention Notification
The system includes functionality to notify users who are mentioned in a comment.
The extractMentionedUserIds utility function parses the comment content (expected to be JSON) to find user IDs marked as 'mention' nodes.
When a comment is created or updated, if new mentions are detected, the CommentMentionNotifierService is used to send notifications to the mentioned users. This process is fire-and-forget to avoid blocking comment operations.
Sources: apps/api/src/comments/comments.service.ts, apps/api/src/comments/comments.service.ts, apps/api/src/comments/comments.service.ts
Authentication and Authorization
The CommentsController uses HybridAuthGuard to support both JWT (session-based) and API key authentication.
The @AuthContext() decorator provides an AuthContextType object, which indicates whether the request originated from an API key (isApiKey) and provides the userId.
Sources: apps/api/src/comments/comments.controller.ts, apps/api/src/comments/comments.controller.ts, apps/api/src/comments/comments.controller.ts, apps/api/src/comments/comments.controller.ts
Module Structure
The CommentsModule integrates all necessary components for the Comments System.
@Module({
imports: [AuthModule, AttachmentsModule],
controllers: [CommentsController],
providers: [CommentsService, CommentMentionNotifierService, NovuService],
exports: [CommentsService],
})
export class CommentsModule {}imports:AuthModule: Provides authentication-related services and guards, includingHybridAuthGuard.AttachmentsModule: ProvidesAttachmentsServicefor handling file uploads and management.
controllers: RegistersCommentsControllerto handle API routes.providers: RegistersCommentsService,CommentMentionNotifierService, andNovuServiceas injectable services.exports: MakesCommentsServiceavailable for injection into other modules if needed.
On This Page
Architecture OverviewData Transfer Objects (DTOs)Request DTOsResponse DTOsAPI EndpointsCore Logic: CommentsServiceEntity Access ValidationCreating a CommentValidate Entity AccessVerify MemberCreate Comment and Attachments in TransactionNotify Mentioned UsersRetrieving CommentsUpdating a CommentDeleting a CommentMention NotificationAuthentication and AuthorizationModule Structure