Skip to content

refactor DTOs to domain modules with validation tests#138

Merged
Villarley merged 1 commit intoVolunChain:mainfrom
martinvibes:refac_dtos
Jul 2, 2025
Merged

refactor DTOs to domain modules with validation tests#138
Villarley merged 1 commit intoVolunChain:mainfrom
martinvibes:refac_dtos

Conversation

@martinvibes
Copy link
Copy Markdown

@martinvibes martinvibes commented Jul 1, 2025

🚀 Volunchain Pull Request

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


📌 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 pull request addresses issue #128 by moving all DTOs to their respective domain modules and enhancing validation with comprehensive unit tests. The changes align with the Domain-Driven Design principles and the project's architecture standards.

🔧 Changes Made

  • 🚚 Moved DTOs from src/dtos/ to src/modules/auth/dto/ for better modularity.
  • ✅ Added unit tests for RegisterDTO, ResendVerificationDTO, and VerifyEmailDTO to cover validation edge cases.
  • 🔍 Updated import paths in related files to reflect the new DTO locations.
  • 🗑️ Prepared for the removal of the legacy src/dtos/ directory (pending final verification).
  • 📦 Updated jest.config.ts and package.json to support new test configurations.
  • 🧪 Introduced mock utilities in tests/mocks/prisma.ts for testing.

📂 Files Touched

  • jest.config.ts (modified)
  • package.json (modified)
  • src/dtos/emailVerification.dto.ts (modified)
  • src/dtos/resendVerificationDTO.ts (modified)
  • src/dtos/verifyEmailDTO.ts (modified)
  • src/modules/auth/tests/dto/emailVerification.dto.test.ts (new)
  • src/modules/auth/tests/dto/resendVerificationDTO.test.ts (new)
  • src/modules/auth/tests/dto/verifyEmailDTO.test.ts (new)
  • src/modules/auth/dto/emailVerification.dto.ts (new)
  • src/modules/auth/dto/resendVerificationDTO.ts (new)
  • src/modules/auth/dto/verifyEmailDTO.ts (new)
  • tests/mocks/prisma.ts (new)
  • tests/dto-validation.test.ts (new)
  • tests/email.test.ts (modified)

✅ Definition of Done

  • All DTOs are colocated within the auth domain module.
  • Validations are consistently implemented using class-validator.
  • Unit tests cover edge cases for all DTOs.
  • Legacy src/dtos/ directory will be removed after final validation.

🧪 Testing

  • Ran DB_TYPE=sqlite npm test to ensure all tests pass.
  • Verified test coverage for DTO validations.

📢 Next Steps

  • 🔍 Verify DTO usage in controllers and services.
  • 🗑️ Remove src/dtos/ directory after confirmation.
  • 🎯 Merge this draft PR and notify via Telegram for further review.

📸 Evidence (A photo is required as evidence)

Screenshot 2025-07-01 at 3 16 43 pm

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!

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 1, 2025

Walkthrough

This change migrates all DTOs for email verification and user registration from the global src/dtos/ directory to the src/modules/auth/dto/ module, unifies and enhances validation using class-validator, and adds comprehensive unit tests for DTO validation edge cases. The legacy DTO files are deleted. Jest configuration and test mocks are updated to support the new structure.

Changes

Files/Paths Change Summary
jest.config.ts, package.json Refactored Jest config to ES module syntax, expanded roots/testMatch, added Prisma mock mapping, new test scripts
src/dtos/emailVerification.dto.ts, src/dtos/verifyEmailDTO.ts Deleted legacy DTO files from global directory
src/modules/auth/dto/emailVerification.dto.ts, src/modules/auth/dto/verifyEmailDTO.ts Added new DTO classes/interfaces with unified validation in the auth module
src/modules/auth/tests/dto/emailVerification.dto.test.ts, src/modules/auth/tests/dto/resendVerificationDTO.test.ts, src/modules/auth/tests/dto/verifyEmailDTO.test.ts, tests/dto-validation.test.ts Added unit tests for DTO validation edge cases
tests/mocks/prisma.ts Added a mock Prisma client for tests
tests/email.test.ts Minor formatting and style changes only

Sequence Diagram(s)

sequenceDiagram
  participant Test as Unit Test
  participant RegisterDTO as RegisterDTO
  participant Validator as class-validator

  Test->>RegisterDTO: Create instance with test data
  Test->>RegisterDTO: Call static validate()
  RegisterDTO->>Validator: validate(instance)
  Validator-->>RegisterDTO: Validation errors (if any)
  RegisterDTO-->>Test: Return errors
  Test->>Test: Assert error count and properties
Loading

Assessment against linked issues

Objective Addressed Explanation
Move DTOs to the correct module, colocate in src/modules/<domain>/dto/ (#128)
Normalize validations using class-validator (#128)
Write unit tests for validation edge cases in src/modules/<domain>/__tests__/dto/ (#128)
Delete src/dtos/ after migration (#128)

Assessment against linked issues: Out-of-scope changes

Code Change (file_path) Explanation
Added Prisma mock implementation (tests/mocks/prisma.ts) This addition is not explicitly mentioned in the objectives but is likely test-infrastructure.

Poem

🐇
The DTOs have hopped to their home,
In modules where bunnies now roam.
With validators neat,
And tests that can’t be beat,
Our code garden’s tidy—no more to comb!
🌱✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-01T15_19_40_984Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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.

@martinvibes
Copy link
Copy Markdown
Author

@Villarley kindly review everything works as expected all test are passing

Copy link
Copy Markdown

@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: 5

🧹 Nitpick comments (6)
tests/__mocks__/prisma.ts (1)

1-6: Remove unnecessary constructor as flagged by static analysis.

The mock implementation is well-structured and follows good patterns for testing. However, the empty constructor is unnecessary and should be removed.

Apply this diff to address the static analysis hint:

 export const PrismaClient = class {
-  constructor() {}
 };
src/modules/auth/__tests__/dto/emailVerification.dto.test.ts (3)

50-55: Remove redundant test case.

This test case duplicates the email format validation already covered in lines 26-36. Both test invalid email formats but this one provides less specific assertions.

Consider removing this test case to eliminate redundancy:

-  it("should fail with invalid email", async () => {
-    const dto = new RegisterDTO();
-    dto.email = "invalid-email";
-    const errors = await RegisterDTO.validate(dto);
-    expect(errors.length).toBeGreaterThan(0);
-  });

15-24: Enhance test assertions for required fields validation.

The test correctly identifies missing required fields but doesn't verify the specific validation messages or constraint types, making it less robust for catching validation decorator changes.

Consider adding constraint-specific assertions similar to the pattern used in tests/dto-validation.test.ts:

   it("should validate required fields", async () => {
     const dto = new RegisterDTO({
       email: "john.doe@example.com",
       password: "SecurePassword123",
     });
     const errors = await RegisterDTO.validate(dto);
     expect(errors).toHaveLength(2);
     expect(errors[0].property).toBe("name");
     expect(errors[1].property).toBe("wallet");
+    expect(errors[0].constraints?.isNotEmpty).toBeDefined();
+    expect(errors[1].constraints?.isNotEmpty).toBeDefined();
   });

1-56: Consider adding edge case tests for better coverage.

The current test suite covers the main validation scenarios but could benefit from additional edge cases to ensure robust validation.

Consider adding tests for:

  • Empty strings vs undefined values (due to constructor defaulting behavior)
  • Maximum length constraints if applicable
  • Special characters in wallet addresses
  • Password complexity requirements beyond length

Example:

it("should handle undefined vs empty string fields", async () => {
  const dto = new RegisterDTO({ name: undefined, wallet: undefined });
  const errors = await RegisterDTO.validate(dto);
  expect(errors).toHaveLength(4); // name, wallet, email, password all invalid
});
tests/dto-validation.test.ts (1)

1-58: Consider consolidating duplicate test coverage.

This test file duplicates some validation scenarios already covered in src/modules/auth/__tests__/dto/emailVerification.dto.test.ts. While the constraint-specific assertions here are more thorough, consider whether both test files are necessary.

Options to consider:

  1. Merge the detailed constraint checking from this file into the domain-specific test file
  2. Keep this as a general DTO validation suite and remove duplicate cases from the domain test
  3. Clearly differentiate the scope of each test file in comments

The current approach provides good coverage but may lead to maintenance overhead with duplicate test scenarios.

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

35-37: Add return type annotation for better type safety.

The static validate method should explicitly declare its return type for better TypeScript support and documentation.

- static validate(dto: RegisterDTO) {
+ static validate(dto: RegisterDTO): Promise<ValidationError[]> {
   return validate(dto);
 }

You'll need to import ValidationError from class-validator.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8444abe and dc34c04.

📒 Files selected for processing (12)
  • jest.config.ts (1 hunks)
  • package.json (1 hunks)
  • src/dtos/emailVerification.dto.ts (0 hunks)
  • src/dtos/verifyEmailDTO.ts (0 hunks)
  • src/modules/auth/__tests__/dto/emailVerification.dto.test.ts (1 hunks)
  • src/modules/auth/__tests__/dto/resendVerificationDTO.test.ts (1 hunks)
  • src/modules/auth/__tests__/dto/verifyEmailDTO.test.ts (1 hunks)
  • src/modules/auth/dto/emailVerification.dto.ts (1 hunks)
  • src/modules/auth/dto/verifyEmailDTO.ts (1 hunks)
  • tests/__mocks__/prisma.ts (1 hunks)
  • tests/dto-validation.test.ts (1 hunks)
  • tests/email.test.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • src/dtos/verifyEmailDTO.ts
  • src/dtos/emailVerification.dto.ts
🧰 Additional context used
🧬 Code Graph Analysis (5)
src/modules/auth/__tests__/dto/emailVerification.dto.test.ts (1)
src/modules/auth/dto/emailVerification.dto.ts (1)
  • RegisterDTO (9-38)
src/modules/auth/__tests__/dto/resendVerificationDTO.test.ts (2)
src/modules/auth/dto/emailVerification.dto.ts (1)
  • ResendVerificationDTO (44-46)
src/modules/auth/dto/resendVerificationDTO.ts (1)
  • ResendVerificationDTO (3-6)
tests/dto-validation.test.ts (1)
src/modules/auth/dto/emailVerification.dto.ts (2)
  • RegisterDTO (9-38)
  • validate (35-37)
src/modules/auth/dto/verifyEmailDTO.ts (1)
src/modules/auth/dto/emailVerification.dto.ts (1)
  • VerifyEmailDTO (40-42)
src/modules/auth/dto/emailVerification.dto.ts (2)
src/modules/auth/dto/verifyEmailDTO.ts (1)
  • VerifyEmailDTO (3-7)
src/modules/auth/dto/resendVerificationDTO.ts (1)
  • ResendVerificationDTO (3-6)
🪛 Biome (1.9.4)
tests/__mocks__/prisma.ts

[error] 2-2: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

🔇 Additional comments (5)
src/modules/auth/dto/verifyEmailDTO.ts (1)

1-7: LGTM! Well-implemented DTO with proper validation.

The class-based DTO with class-validator decorators is a significant improvement over interface-based DTOs, providing runtime validation for the token property. The validation rules are appropriate for an email verification token.

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

1-27: No changes needed: @isemail rejects empty strings

We verified that validator.isEmail('') returns false, so the @IsEmail() decorator already treats empty strings as invalid. The existing tests correctly cover this behavior, and there’s no need to add an @IsNotEmpty() decorator.

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

1-28: LGTM! Comprehensive test coverage with proper runtime validation testing.

The test suite effectively covers all validation scenarios including the important runtime type checking test. The use of as any with the ESLint disable comment is appropriate for testing runtime validation behavior beyond TypeScript's compile-time checks.

tests/email.test.ts (1)

1-95: LGTM! Formatting improvements enhance consistency.

The changes are purely stylistic improvements that standardize quote usage and formatting. The ESLint directive for the unused userId variable is appropriate since it's assigned during registration but not used in subsequent tests.

jest.config.ts (1)

1-37: LGTM! Configuration properly supports new test structure.

The Jest configuration updates appropriately support the DTO test migration:

  • ES module conversion modernizes the config
  • Adding <rootDir>/src to roots enables test discovery in the new location
  • Extended test patterns correctly match the new test file locations
  • Prisma mock mapping provides proper test isolation
  • Formatting improvements enhance consistency

The configuration changes align well with the PR objectives of reorganizing DTOs into domain modules with comprehensive testing.

Copy link
Copy Markdown
Contributor

@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 474fd03 into VolunChain:main Jul 2, 2025
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 5, 2025
10 tasks
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.

Move All DTOs to Their Domain Modules (dto/)

2 participants