Skip to content

Conversation

@JosueBrenes
Copy link
Contributor

@JosueBrenes JosueBrenes commented Aug 5, 2025

🚀 Volunchain Pull Request

Mark with an x all the checkboxes that apply (like [x])

  • Closes #
  • Added tests (if necessary)
  • Run tests
  • Run formatting
  • Evidence attached
  • Commented the code

📌 Type of Change

  • Documentation (updates to README, docs, or comments)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

📝 Changes description

This PR enhances input validation across the user, project, and organization modules by replacing the existing express-validator logic with a DTO-based validation approach using class-validator. Each controller route now uses typed DTOs with proper @Is* decorators to validate and sanitize incoming data. This shift aligns the API layer with our Domain-Driven Design (DDD) architecture and ensures that all inputs are clean, consistent, and secure before any processing occurs. Controllers were updated to integrate this mechanism with robust error handling for invalid inputs. The refactor ensures long-term maintainability and improved input hygiene throughout the application.


⏰ Time spent breakdown

  • 🔍 Audit of current input validation logic: 45 min
  • 🧱 Creation of DTOs for user, project, and organization modules: 1h 30min
  • 🔁 Refactor of controller routes to use DTOs: 1h
  • 🧪 Writing new unit and integration tests: 45 min
  • 🧹 Linting, formatting, and CI validation: 30 min

Total: ~4h 30min


🌌 Comments

  • The API is now fully compliant with DTO-based validation.
  • All invalid inputs return structured error messages.
  • This improves developer experience and ensures safe handling of data across modules.

Thank you for contributing to Volunchain, we are glad that you have chosen us as your project of choice and we hope that you continue to contribute to this great project, so that together we can make our mark at the top!

Summary by CodeRabbit

  • New Features

    • Introduced centralized DTO-based validation for API requests, enhancing type safety and consistent error handling across endpoints.
    • Added new authentication, organization, and wallet validation endpoints with structured request validation.
    • Implemented reusable validation middleware for bodies, params, and queries.
  • Bug Fixes

    • Improved validation error messages throughout DTOs for clearer feedback on invalid input.
  • Documentation

    • Added a comprehensive guide on DTO-based validation, migration steps, and best practices.
  • Tests

    • Added tests for validation middleware to ensure accurate request validation and error responses.
  • Chores

    • Updated .gitignore to exclude .claude/ directory.

…, email, password, and Stellar wallet address
@coderabbitai
Copy link

coderabbitai bot commented Aug 5, 2025

Walkthrough

This set of changes introduces a comprehensive DTO-based validation system using class-validator and class-transformer across multiple modules and routes. It adds new DTO classes with validation decorators, centralized validation middleware, updated route definitions to use DTO validation, enhanced controller typings, and detailed documentation. Associated test suites and shared DTOs for common patterns are also included.

Changes

Cohort / File(s) Change Summary
Documentation & Guide
docs/dto-validation-guide.md
Added a detailed guide explaining the new DTO-based validation system, usage examples, migration steps, and best practices.
Validation Middleware & Shared DTOs
src/shared/middleware/validation.middleware.ts, src/shared/dto/base.dto.ts, src/shared/middleware/__tests__/validation.middleware.test.ts
Introduced generic validation middleware for body, query, and params; added shared DTOs for UUIDs, pagination, and error responses; provided test coverage for middleware logic.
Auth Module DTOs
src/modules/auth/dto/login.dto.ts, src/modules/auth/dto/register.dto.ts, src/modules/auth/dto/resendVerificationDTO.ts, src/modules/auth/dto/verifyEmailDTO.ts, src/modules/auth/dto/wallet-validation.dto.ts
Added new DTOs for login, registration, wallet validation, and updated existing DTOs to include validation decorators with custom error messages.
User Module DTOs
src/modules/user/dto/CreateUserDto.ts, src/modules/user/dto/UpdateUserDto.ts
Enhanced DTOs with validation decorators, stricter property constraints, and improved optionality and error messages.
Organization Module DTOs & Controller
src/modules/organization/presentation/dto/create-organization.dto.ts, src/modules/organization/presentation/dto/update-organization.dto.ts, src/modules/organization/presentation/controllers/organization.controller.ts
Updated DTOs to include explicit error messages, improved controller typings to leverage DTOs for type safety and clarity.
Project Module DTOs
src/modules/project/dto/CreateProjectDto.ts, src/modules/project/dto/UpdateProjectDto.ts
Changed interfaces to classes, added validation decorators, and enforced property constraints with custom messages.
NFT Module DTO & Routes
src/modules/nft/dto/create-nft.dto.ts, src/routes/nftRoutes.ts
Converted interface to class, added validation decorators, and updated routes to use DTO validation middleware for all endpoints.
Messaging Module DTO
src/modules/messaging/dto/message.dto.ts
Enhanced validation decorators with custom error messages and stricter UUID validation.
Volunteer Module DTOs
src/modules/volunteer/dto/volunteer.dto.ts
Converted interfaces to classes, added validation decorators, and enforced constraints with explicit messages.
New v2 API Routes
src/routes/v2/auth.routes.ts, src/routes/v2/organization.routes.ts
Introduced new router files for authentication and organization endpoints, applying DTO-based validation middleware throughout.
.gitignore
.gitignore
Added .claude/ directory to ignore list.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ExpressRoute
    participant ValidationMiddleware
    participant Controller

    Client->>ExpressRoute: Sends HTTP request (body/query/params)
    ExpressRoute->>ValidationMiddleware: Passes request data
    ValidationMiddleware->>ValidationMiddleware: Transforms & validates DTO
    alt Validation fails
        ValidationMiddleware-->>Client: Responds 400 with error details
    else Validation passes
        ValidationMiddleware->>Controller: Calls next() with validated data
        Controller-->>Client: Sends response
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20-25 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • Villarley

Poem

In fields of code, a rabbit hops,
With DTOs and rules, it never stops.
Validators check each string and key,
Ensuring data’s error-free.
Middleware guards the garden gate,
While docs and tests illuminate.
🐇✨ Now validation’s truly great!

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Member

@Villarley Villarley left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Villarley Villarley merged commit 3b3b6cc into VolunChain:main Aug 5, 2025
0 of 2 checks passed
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Nitpick comments (6)
.gitignore (1)

37-40: Addition is fine, but tweak formatting & pattern for completeness

.DS_Store and .claude/ are appropriate additions, yet a few polish points will keep the file tidy:

  1. Group .DS_Store with other OS-generated artefacts (e.g., directly after the existing .DS_Store comment block, if present) for easier scanning.
  2. The comment # Claude has an extra trailing space – remove it for consistency with the rest of the file.
  3. To ignore both a directory and any file that might be called .claude, list both patterns or drop the slash:
-# Claude 
-.claude/
+# Claude
+.claude
+.claude/

Very minor, but keeps the ignore rules predictable and consistent.

src/modules/messaging/dto/message.dto.ts (1)

4-6: Consider adding length validation to content field.

While the string and non-empty validation is correct, consider adding @MaxLength() decorator to prevent extremely long messages that could impact performance or storage.

  @IsString({ message: "Content must be a string" })
  @IsNotEmpty({ message: "Content is required" })
+ @MaxLength(5000, { message: "Content cannot exceed 5000 characters" })
  content: string;
src/modules/auth/dto/wallet-validation.dto.ts (1)

3-35: Stellar wallet validation is technically correct but has code duplication.

The validation logic properly implements Stellar address format requirements:

  • Correct 56-character length constraint
  • Accurate regex pattern for Stellar addresses (G + 55 base32 characters)
  • Clear error messages

However, consider refactoring to eliminate duplication between the two DTOs.

Create a base class or use composition to avoid duplicating wallet validation:

class BaseWalletDto {
  @IsString({ message: "Wallet address must be a string" })
  @MinLength(56, { message: "Stellar wallet address must be 56 characters long" })
  @MaxLength(56, { message: "Stellar wallet address must be 56 characters long" })
  @Matches(/^G[A-Z2-7]{55}$/, { message: "Invalid Stellar wallet address format" })
  walletAddress: string;
}

export class ValidateWalletFormatDto extends BaseWalletDto {}

export class VerifyWalletDto extends BaseWalletDto {
  @IsString({ message: "Signature must be a string" })
  signature: string;

  @IsString({ message: "Message must be a string" })
  message: string;
}
src/shared/middleware/validation.middleware.ts (1)

44-49: Enhance error handling with proper logging.

The generic error handling should include logging for debugging purposes while maintaining security by not exposing internal errors to clients.

-    } catch {
+    } catch (error) {
+      console.error('Validation middleware error:', error);
       res.status(500).json({
         success: false,
         error: "Internal server error during validation",
       });
     }

Apply similar changes to the other validation functions for consistency.

src/modules/organization/presentation/controllers/organization.controller.ts (2)

119-129: Simplify default value handling using DTO defaults.

The PaginationQueryDto already provides default values (page = 1, limit = 10), so manual fallbacks are unnecessary. The validation middleware should handle these defaults automatically.

-      const { page, limit, search } = req.query;
-
-      const organizations = await this.getAllOrganizationsUseCase.execute({
-        page: page || 1,
-        limit: limit || 10,
-        search,
-      });
+      const { page, limit, search } = req.query;
+
+      const organizations = await this.getAllOrganizationsUseCase.execute({
+        page,
+        limit,
+        search,
+      });

134-136: Remove duplicate default value handling.

Since the DTO provides defaults and they're already handled in the use case call, remove the duplicate fallback logic here.

         pagination: {
-          page: page || 1,
-          limit: limit || 10,
+          page,
+          limit,
           total: organizations.length,
         },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ea17b9a and aa074d7.

📒 Files selected for processing (23)
  • .gitignore (1 hunks)
  • docs/dto-validation-guide.md (1 hunks)
  • src/modules/auth/dto/login.dto.ts (1 hunks)
  • src/modules/auth/dto/register.dto.ts (1 hunks)
  • src/modules/auth/dto/resendVerificationDTO.ts (1 hunks)
  • src/modules/auth/dto/verifyEmailDTO.ts (1 hunks)
  • src/modules/auth/dto/wallet-validation.dto.ts (1 hunks)
  • src/modules/messaging/dto/message.dto.ts (1 hunks)
  • src/modules/nft/dto/create-nft.dto.ts (1 hunks)
  • src/modules/organization/presentation/controllers/organization.controller.ts (6 hunks)
  • src/modules/organization/presentation/dto/create-organization.dto.ts (1 hunks)
  • src/modules/organization/presentation/dto/update-organization.dto.ts (1 hunks)
  • src/modules/project/dto/CreateProjectDto.ts (1 hunks)
  • src/modules/project/dto/UpdateProjectDto.ts (1 hunks)
  • src/modules/user/dto/CreateUserDto.ts (1 hunks)
  • src/modules/user/dto/UpdateUserDto.ts (1 hunks)
  • src/modules/volunteer/dto/volunteer.dto.ts (1 hunks)
  • src/routes/nftRoutes.ts (1 hunks)
  • src/routes/v2/auth.routes.ts (1 hunks)
  • src/routes/v2/organization.routes.ts (1 hunks)
  • src/shared/dto/base.dto.ts (1 hunks)
  • src/shared/middleware/__tests__/validation.middleware.test.ts (1 hunks)
  • src/shared/middleware/validation.middleware.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/routes/v2/auth.routes.ts (4)
src/shared/middleware/validation.middleware.ts (1)
  • validateDto (15-51)
src/modules/auth/dto/register.dto.ts (1)
  • RegisterDto (9-32)
src/modules/auth/dto/login.dto.ts (1)
  • LoginDto (3-10)
src/modules/auth/dto/wallet-validation.dto.ts (2)
  • ValidateWalletFormatDto (3-15)
  • VerifyWalletDto (17-35)
src/routes/nftRoutes.ts (3)
src/shared/middleware/validation.middleware.ts (2)
  • validateDto (15-51)
  • validateParamsDto (91-127)
src/modules/nft/dto/create-nft.dto.ts (1)
  • CreateNFTDto (3-14)
src/shared/dto/base.dto.ts (1)
  • UuidParamsDto (4-7)
src/modules/organization/presentation/controllers/organization.controller.ts (3)
src/modules/organization/presentation/dto/create-organization.dto.ts (1)
  • CreateOrganizationDto (10-46)
src/shared/dto/base.dto.ts (2)
  • UuidParamsDto (4-7)
  • PaginationQueryDto (9-25)
src/modules/organization/presentation/dto/update-organization.dto.ts (1)
  • UpdateOrganizationDto (11-55)
🔇 Additional comments (35)
src/shared/dto/base.dto.ts (2)

4-7: LGTM! Well-structured UUID parameter validation.

The UuidParamsDto correctly validates UUID v4 format with a clear error message, perfect for route parameter validation.


27-30: LGTM! Clean base response structure.

The BaseResponseDto provides a solid foundation for consistent API responses with clear success indication and optional messaging.

src/modules/auth/dto/verifyEmailDTO.ts (1)

4-5: LGTM! Improved validation error messages.

The addition of custom error messages enhances user experience by providing clear, actionable feedback for validation failures.

src/modules/auth/dto/resendVerificationDTO.ts (1)

4-4: LGTM! Consistent error messaging improvement.

The custom error message for email validation provides clearer feedback and aligns with the enhanced DTO validation approach.

src/routes/v2/organization.routes.ts (2)

18-22: Fix missing comma after validation middleware.

There's a syntax error - missing comma after the validation middleware.

router.post(
  "/",
- validateDto(CreateOrganizationDto)
+ validateDto(CreateOrganizationDto),
  // organizationController.createOrganization
);

Likely an incorrect or invalid review comment.


39-45: Fix missing comma after validation middleware.

Missing comma after the validation middleware will prevent proper route handling.

router.put(
  "/:id",
  auth.authMiddleware,
  validateParamsDto(UuidParamsDto),
- validateDto(UpdateOrganizationDto)
+ validateDto(UpdateOrganizationDto),
  // organizationController.updateOrganization
);

Likely an incorrect or invalid review comment.

src/modules/project/dto/CreateProjectDto.ts (1)

11-28: LGTM! Excellent DTO transformation with comprehensive validation.

The conversion from interface to class with class-validator decorators is well-executed:

  • Appropriate length constraints for title (3-200) and description (10-2000)
  • Proper UUID validation for organizationId
  • Optional status with enum validation
  • Clear, descriptive error messages throughout

This follows the established DTO validation pattern perfectly.

src/modules/auth/dto/login.dto.ts (1)

1-10: LGTM! Clean and comprehensive validation implementation.

The LoginDto properly validates both email format and password presence with clear error messages. The validation decorators are correctly applied and the custom error messages provide good user feedback.

src/modules/organization/presentation/dto/update-organization.dto.ts (1)

11-55: LGTM! Comprehensive validation with proper security constraints.

The UpdateOrganizationDto provides thorough validation for all organization fields with appropriate length constraints and clear error messages. The optional field handling and input size limits help prevent potential abuse while maintaining usability.

src/modules/organization/presentation/dto/create-organization.dto.ts (1)

10-46: LGTM! Well-structured validation for organization creation.

The CreateOrganizationDto properly validates all required fields with appropriate constraints. The 8-character minimum password requirement follows security best practices, and the validation rules are consistent with the update DTO.

src/routes/v2/auth.routes.ts (3)

1-11: LGTM! Clean imports and well-organized validation setup.

The import structure properly brings in the validation middleware and all required DTOs for the authentication routes.


12-16: Good documentation of incomplete implementation.

The comments clearly indicate this is example integration and that controller instantiation is needed.


59-59: LGTM! Proper export structure.

The default export follows Express routing conventions correctly.

src/modules/auth/dto/register.dto.ts (2)

1-8: LGTM! Proper imports for validation decorators.

All necessary validation decorators are imported correctly for the DTO implementation.


9-22: LGTM! Solid validation for core registration fields.

The validation for name, email, and password fields is well-implemented with appropriate constraints and clear error messages. The 8-character minimum password requirement follows security best practices.

src/modules/volunteer/dto/volunteer.dto.ts (2)

9-34: Excellent validation implementation!

The DTO validation rules are well-designed with appropriate constraints:

  • Reasonable length limits for each field based on business context
  • Clear, user-friendly error messages
  • Proper UUID validation for referential integrity
  • Optional incentive field handled correctly

36-61: Consistent validation for update operations.

The optional validation decorators are properly applied with the same constraints as the create DTO. However, note that projectId is not included in the update DTO - verify this is intentional to prevent project reassignment through updates.

src/modules/messaging/dto/message.dto.ts (1)

8-20: UUID validation is properly implemented.

Consistent use of UUID v4 validation with clear error messages across all ID fields. The combination of @IsUUID(4) and @IsNotEmpty() ensures robust validation.

src/modules/project/dto/UpdateProjectDto.ts (1)

11-31: Well-structured update DTO with proper validation.

The conversion from interface to class with validation decorators is correctly implemented:

  • Appropriate optional validation for all fields
  • Consistent length constraints matching business requirements
  • Proper enum validation for status field
  • UUID validation for organizational references
src/routes/nftRoutes.ts (2)

12-12: Proper DTO validation integration for POST route.

The POST route correctly uses validateDto(CreateNFTDto) middleware to validate the request body against the CreateNFTDto schema.


14-18: Consistent parameter validation for ID-based routes.

Both routes correctly use :id parameter with UuidParamsDto validation, ensuring proper UUID validation for resource identification.

Also applies to: 26-30

src/shared/middleware/__tests__/validation.middleware.test.ts (4)

1-23: LGTM! Comprehensive test setup.

The imports are well-organized and include all necessary dependencies. The reflect-metadata import is crucial for class-validator decorators to work properly. The Jest setup follows standard patterns with proper mocking.


25-79: LGTM! Comprehensive validateDto testing.

The tests cover both success and failure scenarios effectively:

  • Valid data test confirms middleware passes through to next()
  • Invalid data test verifies proper error response structure with 400 status
  • Test data appropriately violates validation rules (short strings, invalid email format)
  • Assertions properly check both the happy path and error handling

81-113: LGTM! Proper UUID parameter validation testing.

The tests effectively validate UUID parameter handling:

  • Uses a valid UUID v4 format for the success case
  • Uses clearly invalid format for the failure case
  • Follows consistent testing patterns with proper assertions

115-151: LGTM! Effective query parameter validation testing.

The tests properly validate pagination query parameters:

  • Valid case uses appropriate pagination values with optional search parameter
  • Invalid case tests boundary conditions (non-numeric page, negative limit)
  • Properly handles the fact that query parameters come as strings and require transformation
src/modules/nft/dto/create-nft.dto.ts (1)

1-14: LGTM! Well-structured DTO with appropriate validations.

The DTO implementation follows best practices:

  • Proper UUID v4 validation for ID fields with descriptive error messages
  • Reasonable length constraints for description (10-1000 characters)
  • Consistent use of custom error messages for better user experience
  • Clean migration from interface to class-based validation
src/modules/user/dto/UpdateUserDto.ts (1)

10-45: Stellar wallet regex validation confirmed

The regex /^G[A-Z2-7]{55}$/ correctly enforces the 56-character StrKey Base32 format for Stellar addresses. All validations in UpdateUserDto are appropriate—approving as-is.

src/modules/user/dto/CreateUserDto.ts (1)

10-41: LGTM! Consistent validation patterns for user creation.

The DTO implementation demonstrates good design:

  • Appropriate required fields for user creation (name, lastName, email, password)
  • Optional wallet field allows flexibility in user registration flow
  • Validation rules are consistent with UpdateUserDto for maintainability
  • Same comprehensive validation patterns with descriptive error messages
docs/dto-validation-guide.md (1)

1-257: Excellent comprehensive documentation!

This guide provides outstanding coverage of the DTO validation system:

  • Clear architectural overview with all core components
  • Practical usage examples that match the actual implementation
  • Detailed migration guide from express-validator to class-validator
  • Comprehensive list of validation decorators and patterns
  • Standardized error response format
  • Helpful best practices and migration checklist

This documentation will significantly improve developer experience and ensure consistent implementation across the codebase.

src/shared/middleware/validation.middleware.ts (1)

5-13: LGTM! Well-structured validation error interface.

The interface provides clear typing for validation error responses with appropriate type discrimination using the literal false type for the success field.

src/modules/organization/presentation/controllers/organization.controller.ts (5)

11-14: LGTM! Proper use of shared DTOs.

The imports correctly utilize shared DTO classes for common validation patterns, promoting consistency and reusability across the application.


26-31: LGTM! Improved type safety with DTO typing.

The method signature correctly types the request body as CreateOrganizationDto, providing better type safety and IntelliSense support.


43-43: LGTM! Consistent UUID parameter typing.

The method signature correctly uses the shared UuidParamsDto for type-safe UUID parameter validation.


67-76: LGTM! Comprehensive typing for update operation.

The method signature correctly types both route parameters and request body with their respective DTOs, ensuring full type safety for the update operation.


98-98: LGTM! Consistent UUID parameter typing.

The method signature maintains consistency with other methods by using UuidParamsDto for UUID parameter validation.

Comment on lines +23 to +32
@IsOptional()
@IsString({ message: "Wallet address must be a string" })
@MinLength(56, {
message: "Stellar wallet address must be 56 characters long",
})
@MaxLength(56, {
message: "Stellar wallet address must be 56 characters long",
})
walletAddress?: string;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add regex pattern validation for Stellar wallet addresses.

The wallet address validation only checks length but missing format validation. Based on other wallet DTOs in the codebase, Stellar addresses should match the pattern /^G[A-Z2-7]{55}$/.

 @IsOptional()
 @IsString({ message: "Wallet address must be a string" })
 @MinLength(56, {
   message: "Stellar wallet address must be 56 characters long",
 })
 @MaxLength(56, {
   message: "Stellar wallet address must be 56 characters long",
 })
+@Matches(/^G[A-Z2-7]{55}$/, {
+  message: "Invalid Stellar wallet address format",
+})
 walletAddress?: string;

You'll also need to import Matches from class-validator:

 import {
   IsString,
   IsEmail,
   MinLength,
   MaxLength,
   IsOptional,
+  Matches,
 } from "class-validator";
🤖 Prompt for AI Agents
In src/modules/auth/dto/register.dto.ts around lines 23 to 32, the walletAddress
field currently validates only the length but lacks format validation. To fix
this, import the Matches decorator from class-validator and add a
@Matches(/^G[A-Z2-7]{55}$/, { message: "Invalid Stellar wallet address format"
}) decorator to walletAddress. This will enforce the correct Stellar address
pattern as per the codebase standards.

Comment on lines +20 to 24
router.get(
"/users/:userId/nfts",
validateParamsDto(UuidParamsDto),
NFTController.getNFTsByUserId
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Parameter validation mismatch will cause failures.

The route uses :userId parameter but UuidParamsDto expects an id property. This mismatch will cause validation failures.

Create a dedicated DTO for this route or use a different approach:

// Option 1: Create UserIdParamsDto
export class UserIdParamsDto {
  @IsUUID(4, { message: "User ID must be a valid UUID" })
  userId: string;
}

// Then use it in the route:
router.get(
  "/users/:userId/nfts",
  validateParamsDto(UserIdParamsDto),
  NFTController.getNFTsByUserId
);
🤖 Prompt for AI Agents
In src/routes/nftRoutes.ts around lines 20 to 24, the route parameter is named
userId but the validation DTO UuidParamsDto expects an id property, causing
validation failures. To fix this, create a new DTO class UserIdParamsDto with a
userId property decorated with the appropriate UUID validation, then update the
route to use validateParamsDto(UserIdParamsDto) instead of UuidParamsDto.

Comment on lines +17 to +57
// POST /auth/register - User registration
router.post(
"/register",
validateDto(RegisterDto)
// authController.register
);

// POST /auth/login - User login
router.post(
"/login",
validateDto(LoginDto)
// authController.login
);

// POST /auth/resend-verification - Resend email verification
router.post(
"/resend-verification",
validateDto(ResendVerificationDTO)
// authController.resendVerificationEmail
);

// POST /auth/verify-email - Verify email with token
router.post(
"/verify-email",
validateDto(VerifyEmailDTO)
// authController.verifyEmail
);

// POST /auth/validate-wallet-format - Validate wallet address format
router.post(
"/validate-wallet-format",
validateDto(ValidateWalletFormatDto)
// authController.validateWalletFormat
);

// POST /auth/verify-wallet - Verify wallet ownership
router.post(
"/verify-wallet",
validateDto(VerifyWalletDto)
// authController.verifyWallet
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify controller integration before deployment.

The route structure and validation middleware integration look excellent. However, the controller methods are currently commented out as placeholders. Ensure that proper controller implementations are added before deploying these routes to prevent 404 errors.


🏁 Script executed:

#!/bin/bash
# Description: Check if there are existing auth controller implementations that should be integrated
# Expected: Find auth controller files with methods that match these route handlers

echo "Searching for auth controller implementations..."
fd -e ts -e js "auth.*controller" --type f

echo -e "\nSearching for auth controller methods..."
rg -A 5 "register|login|resendVerification|verifyEmail|validateWallet|verifyWallet" --type ts --type js

Length of output: 49335


Wire up AuthController in v2 routes

The DTO validation is in place, but none of the routes actually invoke your controller logic—each handler is still commented out and only a 501‐stub exists. Before deploying, you need to import and attach the real (or fully implemented) AuthController methods in src/routes/v2/auth.routes.ts.

• File: src/routes/v2/auth.routes.ts (lines 17–57)

  • Uncomment and add the controller after validateDto(...), e.g.:
    import AuthController from "../../modules/auth/presentation/controllers/Auth.controller";
    
    router.post(
      "/register",
      validateDto(RegisterDto),
      AuthController.register
    );
    // …and so on for login, resendVerificationEmail, verifyEmail, validateWalletFormat, verifyWallet

• Ensure you replace or extend the stub in
src/modules/auth/presentation/controllers/Auth.controller.stub.ts
with your real service calls (right now it always returns 501).
• Run a quick smoke test against each route to confirm no 404s/501s remain.

🤖 Prompt for AI Agents
In src/routes/v2/auth.routes.ts between lines 17 and 57, the route handlers are
currently commented out and only DTO validation is active, resulting in 501
responses. To fix this, import AuthController from the appropriate path and
uncomment each route handler, attaching the corresponding AuthController method
after the validateDto call for each route. Also, update the stub controller in
src/modules/auth/presentation/controllers/Auth.controller.stub.ts to implement
real service logic instead of returning 501. Finally, test each route to ensure
they respond correctly without 404 or 501 errors.

Comment on lines +25 to +29
router.get(
"/",
validateQueryDto(PaginationQueryDto)
// organizationController.getAllOrganizations
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix missing comma after validation middleware.

Missing comma after the validation middleware will cause a syntax error.

router.get(
  "/",
- validateQueryDto(PaginationQueryDto)
+ validateQueryDto(PaginationQueryDto),
  // organizationController.getAllOrganizations
);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
router.get(
"/",
validateQueryDto(PaginationQueryDto)
// organizationController.getAllOrganizations
);
router.get(
"/",
validateQueryDto(PaginationQueryDto),
// organizationController.getAllOrganizations
);
🤖 Prompt for AI Agents
In src/routes/v2/organization.routes.ts around lines 25 to 29, there is a
missing comma after the validateQueryDto(PaginationQueryDto) middleware in the
router.get call. Add a comma immediately after this middleware to separate it
properly from the next argument, organizationController.getAllOrganizations, to
fix the syntax error.

Comment on lines +32 to +36
router.get(
"/:id",
validateParamsDto(UuidParamsDto)
// organizationController.getOrganizationById
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix missing comma after validation middleware.

Missing comma after the validation middleware.

router.get(
  "/:id",
- validateParamsDto(UuidParamsDto)
+ validateParamsDto(UuidParamsDto),
  // organizationController.getOrganizationById
);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
router.get(
"/:id",
validateParamsDto(UuidParamsDto)
// organizationController.getOrganizationById
);
router.get(
"/:id",
validateParamsDto(UuidParamsDto),
// organizationController.getOrganizationById
);
🤖 Prompt for AI Agents
In src/routes/v2/organization.routes.ts around lines 32 to 36, there is a
missing comma after the validateParamsDto(UuidParamsDto) middleware in the
router.get call. Add a comma immediately after this middleware to correctly
separate it from the next argument, which is the commented-out
organizationController.getOrganizationById handler.

Comment on lines +16 to +20
@IsOptional()
@Transform(({ value }) => parseInt(value, 10))
@IsInt({ message: "Limit must be an integer" })
@Min(1, { message: "Limit must be at least 1" })
limit?: number = 10;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add maximum limit validation for security.

Consider adding a maximum limit to prevent potential performance issues or DoS attacks from extremely large page sizes.

  @IsOptional()
  @Transform(({ value }) => parseInt(value, 10))
  @IsInt({ message: "Limit must be an integer" })
  @Min(1, { message: "Limit must be at least 1" })
+ @Max(100, { message: "Limit cannot exceed 100" })
  limit?: number = 10;
🤖 Prompt for AI Agents
In src/shared/dto/base.dto.ts around lines 16 to 20, the limit property lacks a
maximum value validation, which could lead to performance or security issues.
Add a @Max decorator with a reasonable upper bound (e.g., 100) to enforce a
maximum limit on the limit property. This will prevent excessively large values
from being accepted.

Comment on lines +32 to +40
export class ErrorResponseDto extends BaseResponseDto {
success: false;
error: string;
details?: Array<{
property: string;
value: unknown;
constraints: string[];
}>;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix type inconsistency in success property.

The success: false literal type conflicts with the parent class's success: boolean declaration, which could cause TypeScript issues.

export class ErrorResponseDto extends BaseResponseDto {
- success: false;
+ success = false;
  error: string;
  details?: Array<{
    property: string;
    value: unknown;
    constraints: string[];
  }>;
}

Alternatively, consider making the base class generic or using a discriminated union approach for better type safety.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export class ErrorResponseDto extends BaseResponseDto {
success: false;
error: string;
details?: Array<{
property: string;
value: unknown;
constraints: string[];
}>;
}
export class ErrorResponseDto extends BaseResponseDto {
success = false;
error: string;
details?: Array<{
property: string;
value: unknown;
constraints: string[];
}>;
}
🤖 Prompt for AI Agents
In src/shared/dto/base.dto.ts around lines 32 to 40, the success property in
ErrorResponseDto is typed as the literal false, conflicting with the boolean
type in the parent BaseResponseDto class. To fix this, change the success
property type in ErrorResponseDto from the literal false to boolean or refactor
the base class to be generic or use a discriminated union pattern to ensure
consistent and type-safe success property declarations across subclasses.

next: NextFunction
): Promise<void> => {
try {
const dto = plainToClass(dtoClass, req.body);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Configure transformation options for better type safety.

The plainToClass transformation should include options to enable automatic type conversion and exclude extraneous properties for better security and type safety.

-      const dto = plainToClass(dtoClass, req.body);
+      const dto = plainToClass(dtoClass, req.body, {
+        enableImplicitConversion: true,
+        excludeExtraneousValues: true,
+      });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const dto = plainToClass(dtoClass, req.body);
const dto = plainToClass(dtoClass, req.body, {
enableImplicitConversion: true,
excludeExtraneousValues: true,
});
🤖 Prompt for AI Agents
In src/shared/middleware/validation.middleware.ts at line 22, the call to
plainToClass lacks transformation options that improve type safety and security.
Update the plainToClass invocation to include options that enable automatic type
conversion and exclude extraneous properties, ensuring only expected fields are
transformed and validated.

next: NextFunction
): Promise<void> => {
try {
const dto = plainToClass(dtoClass, req.query);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Configure transformation options and handle query parameter types properly.

Query parameters need special handling since they come as strings from Express. The transformation should include options to enable type conversion and exclude extraneous values.

-      const dto = plainToClass(dtoClass, req.query);
+      const dto = plainToClass(dtoClass, req.query, {
+        enableImplicitConversion: true,
+        excludeExtraneousValues: true,
+      });
🤖 Prompt for AI Agents
In src/shared/middleware/validation.middleware.ts at line 60, the transformation
of req.query to the DTO class does not handle type conversion or exclude
extraneous values. Update the plainToClass call to include transformation
options that enable type conversion and exclude properties not defined in the
DTO class to properly handle query parameters as strings and ensure correct
validation.

next: NextFunction
): Promise<void> => {
try {
const dto = plainToClass(dtoClass, req.params);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Configure transformation options for route parameter validation.

Route parameters are always strings in Express, so enabling implicit conversion is crucial for proper type transformation.

-      const dto = plainToClass(dtoClass, req.params);
+      const dto = plainToClass(dtoClass, req.params, {
+        enableImplicitConversion: true,
+        excludeExtraneousValues: true,
+      });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const dto = plainToClass(dtoClass, req.params);
const dto = plainToClass(dtoClass, req.params, {
enableImplicitConversion: true,
excludeExtraneousValues: true,
});
🤖 Prompt for AI Agents
In src/shared/middleware/validation.middleware.ts at line 98, the plainToClass
function is used without transformation options, but since route parameters are
always strings in Express, you need to enable implicit type conversion. Fix this
by passing transformation options to plainToClass with {
enableImplicitConversion: true } to ensure proper type conversion of route
parameters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants