Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ✨ add findByEmail use case #94

Merged
merged 6 commits into from
Dec 4, 2024
Merged

Conversation

zhumeisongsong
Copy link
Owner

@zhumeisongsong zhumeisongsong commented Dec 4, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced user retrieval by email and ID with new use cases: GetUserByIdUseCase and GetUserByEmailUseCase.
    • Enhanced UsersService to support both user lookups.
    • Added a new method to retrieve users by email in the repository layer.
  • Bug Fixes

    • Updated tests to ensure accurate functionality for new user retrieval methods.
  • Documentation

    • Updated module configurations to reflect new use cases and removed deprecated GraphQL federation support.

Copy link

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request introduces significant changes across multiple files, primarily focusing on enhancing user retrieval capabilities and integrating GraphQL with Apollo Federation. Key modifications include the addition of new use cases for retrieving users by ID and email, the restructuring of the UsersService to accommodate these changes, and the removal of previous GraphQL federation configurations. The updates also include new tests for the email-based retrieval functionality and adjustments in the repository interfaces to support the new use cases.

Changes

File Change Summary
apps/users/src/app/app.module.ts Integrated Apollo Federation by adding necessary imports and configuring GraphQLModule with federation settings.
libs/auth/interface-adapters/src/lib/auth.module.ts Replaced GetUserUseCase with GetUserByIdUseCase and GetUserByEmailUseCase.
libs/users/application/src/index.ts Updated exports to replace get-user.use-case with get-user-by-id.use-case and get-user-by-email.use-case.
libs/users/application/src/lib/use-cases/get-user-by-email.use-case.spec.ts Added a test suite for GetUserByEmailUseCase to verify user retrieval by email.
libs/users/application/src/lib/use-cases/get-user-by-email.use-case.ts Introduced GetUserByEmailUseCase class with an execute method for email-based user retrieval.
libs/users/application/src/lib/use-cases/get-user-by-id.use-case.spec.ts Renamed tests from GetUserUseCase to GetUserByIdUseCase and updated references.
libs/users/application/src/lib/use-cases/get-user-by-id.use-case.ts Renamed class from GetUserUseCase to GetUserByIdUseCase and simplified the execute method.
libs/users/application/src/lib/users.service.spec.ts Updated references from GetUserUseCase to GetUserByIdUseCase and added tests for email retrieval.
libs/users/application/src/lib/users.service.ts Replaced GetUserUseCase with GetUserByIdUseCase and GetUserByEmailUseCase in the UsersService.
libs/users/domain/src/lib/users.repository.spec.ts Added findByEmail method to MockUsersRepository with corresponding tests.
libs/users/domain/src/lib/users.repository.ts Added findByEmail method to UsersRepository interface.
libs/users/infrastructure/mongoose/src/lib/mongoose-users.repository.ts Added findByEmail method to MongooseUsersRepository for email-based user retrieval.
libs/users/interface-adapters/src/lib/users.module.ts Removed Apollo Federation imports and replaced GetUserUseCase with new user retrieval use cases.

Possibly related issues

Possibly related PRs

🐰 "In the meadow, we hop and play,
With emails and IDs, we find our way.
New cases to fetch, oh what a delight,
Users by email, all day and night!
With GraphQL's magic, our queries take flight,
Hopping through code, everything feels right!" 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 46958c7 and 6635353.

📒 Files selected for processing (2)
  • libs/users/application/src/lib/use-cases/get-user-by-email.use-case.spec.ts (1 hunks)
  • libs/users/application/src/lib/users.service.spec.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/users/application/src/lib/use-cases/get-user-by-email.use-case.spec.ts
🔇 Additional comments (5)
libs/users/application/src/lib/users.service.spec.ts (5)

3-9: LGTM! Import statements and setup are properly implemented.

The necessary use cases are imported and variables are correctly declared.


Line range hint 16-32: LGTM! Test module configuration is complete and correct.

The test setup properly includes and mocks both use cases, addressing previous configuration issues.


35-58: LGTM! getUserById tests are comprehensive and well-structured.

The test cases properly cover both success and failure scenarios with appropriate assertions.


61-84: LGTM! getUserByEmail tests have been properly implemented.

All previous issues have been addressed:

  • Correctly uses GetUserByEmailUseCase instead of GetUserByIdUseCase
  • Properly verifies email-based lookup logic
  • Test data structure appropriately validates email-based scenarios

35-84: Verify test coverage for edge cases.

While the basic success and failure scenarios are well covered, consider adding tests for the following edge cases:

  • Invalid email format
  • Empty email string
  • Null/undefined email

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@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

🧹 Outside diff range and nitpick comments (8)
libs/users/domain/src/lib/users.repository.ts (1)

5-5: Consider adding JSDoc comments

The new findByEmail method is well-designed and consistent with the existing pattern. Consider adding JSDoc comments to document the behavior, especially regarding null returns and email matching criteria (case sensitivity, etc.).

+ /**
+  * Finds a user by their email address
+  * @param email The email address to search for
+  * @returns Promise resolving to User if found, null otherwise
+  */
  findByEmail(email: string): Promise<User | null>;
libs/users/application/src/lib/use-cases/get-user-by-id.use-case.ts (1)

11-13: Consider adding input validation

The execute method could benefit from input validation to handle invalid ID formats or empty strings before querying the repository.

  async execute(id: string): Promise<User | null> {
+   if (!id?.trim()) {
+     throw new Error('Invalid user ID provided');
+   }
    return await this.usersRepository.findById(id);
  }
libs/users/application/src/lib/use-cases/get-user-by-email.use-case.ts (1)

1-14: LGTM! Clean implementation following best practices.

The implementation follows clean architecture principles with proper dependency injection and clear single responsibility.

Consider adding input validation for the email parameter:

 async execute(email: string): Promise<User | null> {
+  if (!email || !email.includes('@')) {
+    throw new Error('Invalid email format');
+  }
   return this.usersRepository.findByEmail(email);
 }
libs/users/interface-adapters/src/lib/users.module.ts (1)

27-29: Consider using a more type-safe MongoDB configuration.

The current configuration could benefit from stronger typing.

Consider using a type-safe configuration:

 MongooseModule.forFeature([
-  { name: UserDocument.name, schema: UserSchema },
+  {
+    name: UserDocument.name,
+    schema: UserSchema,
+    collection: 'users' as const
+  },
 ]),
libs/users/infrastructure/mongoose/src/lib/mongoose-users.repository.ts (1)

29-41: Consider case-insensitive email search and input validation

The implementation works but could be improved in a few ways:

  1. Make email search case-insensitive for better user experience
  2. Add email parameter validation
  3. Extract repeated user mapping logic to reduce duplication

Consider this implementation:

 async findByEmail(email: string): Promise<User | null> {
+  if (!email || typeof email !== 'string') {
+    throw new Error('Invalid email parameter');
+  }
+
-  const userDocument = await this.userModel.findOne({ email }).exec();
+  const userDocument = await this.userModel
+    .findOne({ email: { $regex: new RegExp(`^${email}$`, 'i') } })
+    .exec();

   if (!userDocument) {
     return null;
   }
-  return new User(
-    userDocument.id,
-    userDocument.email,
-    userDocument.firstName,
-    userDocument.lastName,
-  );
+  return this.mapToUser(userDocument);
 }

+ private mapToUser(doc: UserDocument): User {
+   return new User(
+     doc.id,
+     doc.email,
+     doc.firstName,
+     doc.lastName
+   );
+ }
libs/users/application/src/lib/use-cases/get-user-by-id.use-case.spec.ts (1)

4-13: Consider adding error handling test cases

The test suite could benefit from additional test cases to verify:

  1. Invalid ID handling (e.g., malformed ObjectId)
  2. Repository error handling

Example additional test cases:

it('should throw error for invalid ID format', async () => {
  await expect(getUserByIdUseCase.execute('invalid-id'))
    .rejects
    .toThrow('Invalid ID format');
});

it('should handle repository errors', async () => {
  (usersRepository.findById as jest.Mock)
    .mockRejectedValue(new Error('DB error'));
  
  await expect(getUserByIdUseCase.execute('1'))
    .rejects
    .toThrow('Failed to fetch user');
});
libs/users/domain/src/lib/users.repository.spec.ts (1)

46-59: Consider adding edge case tests

The current tests cover the basic success and failure cases. Consider adding tests for:

  • Case-sensitivity handling
  • Email with leading/trailing spaces
  • Special characters in email
test('findByEmail should handle email case-insensitively', async () => {
  const user = await usersRepository.findByEmail('[email protected]');
  expect(user).not.toBeNull();
});

test('findByEmail should handle whitespace', async () => {
  const user = await usersRepository.findByEmail(' [email protected] ');
  expect(user).not.toBeNull();
});
libs/users/application/src/lib/users.service.spec.ts (1)

Line range hint 13-21: Missing GetUserByEmailUseCase provider in test configuration

The test module configuration is missing the GetUserByEmailUseCase provider, which is required for the findByEmail tests. Currently, the tests are incorrectly using GetUserByIdUseCase for email-based lookups.

Add the missing provider:

 providers: [
   UsersService,
   {
     provide: GetUserByIdUseCase,
     useValue: {
       execute: jest.fn(),
     },
   },
+  {
+    provide: GetUserByEmailUseCase,
+    useValue: {
+      execute: jest.fn(),
+    },
+  },
 ],
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4194ec9 and 46958c7.

📒 Files selected for processing (13)
  • apps/users/src/app/app.module.ts (2 hunks)
  • libs/auth/interface-adapters/src/lib/auth.module.ts (2 hunks)
  • libs/users/application/src/index.ts (1 hunks)
  • libs/users/application/src/lib/use-cases/get-user-by-email.use-case.spec.ts (1 hunks)
  • libs/users/application/src/lib/use-cases/get-user-by-email.use-case.ts (1 hunks)
  • libs/users/application/src/lib/use-cases/get-user-by-id.use-case.spec.ts (3 hunks)
  • libs/users/application/src/lib/use-cases/get-user-by-id.use-case.ts (1 hunks)
  • libs/users/application/src/lib/users.service.spec.ts (3 hunks)
  • libs/users/application/src/lib/users.service.ts (1 hunks)
  • libs/users/domain/src/lib/users.repository.spec.ts (2 hunks)
  • libs/users/domain/src/lib/users.repository.ts (1 hunks)
  • libs/users/infrastructure/mongoose/src/lib/mongoose-users.repository.ts (1 hunks)
  • libs/users/interface-adapters/src/lib/users.module.ts (2 hunks)
🔇 Additional comments (9)
libs/users/application/src/index.ts (1)

1-2: LGTM! Clean and focused exports

The exports are well-structured and follow a clear naming convention, properly exposing both ID and email-based user retrieval functionality.

libs/users/application/src/lib/use-cases/get-user-by-id.use-case.ts (1)

5-9: LGTM! Clean implementation following SOLID principles

The class is well-structured with proper dependency injection and clear responsibility.

libs/users/application/src/lib/users.service.ts (1)

4-5: LGTM! Good separation of concerns.

The refactoring improves the code by using specific use cases for each retrieval method, making the code more maintainable and following the single responsibility principle.

Also applies to: 9-12, 15-15, 19-19

libs/users/interface-adapters/src/lib/users.module.ts (1)

3-3: LGTM! Module configuration properly updated.

The module is correctly configured with the new use cases and maintains proper dependency injection.

Also applies to: 18-19

apps/users/src/app/app.module.ts (2)

27-40: LGTM: GraphQL configuration follows best practices

The configuration:

  • ✅ Disables playground in production
  • ✅ Enables schema sorting for consistency
  • ✅ Includes trace plugin for debugging

29-36: Verify federation version compatibility with existing services

The explicit federation version 2 setting is added to address a known issue (nestjs/graphql#2646). Ensure this version is compatible with other federated services in your architecture.

✅ Verification successful

Let me search for other GraphQL module configurations to better understand the federation setup across the codebase.


Federation v2 configuration is correctly aligned across the architecture

The codebase shows a consistent GraphQL Federation setup:

  • Users service is explicitly configured with Federation v2
  • Gateway service uses IntrospectAndCompose which is compatible with Federation v2
  • No conflicting federation versions were found in other services
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other federation version configurations
rg -l "federation.*[12]" --type ts

Length of output: 69


Script:

#!/bin/bash
# Search for GraphQL module configurations and federation settings in the codebase
rg -A 10 "GraphQLModule\.forRoot" --type ts

Length of output: 1628

libs/auth/interface-adapters/src/lib/auth.module.ts (1)

8-8: Verify all GetUserUseCase consumers are updated

The replacement of GetUserUseCase with GetUserByIdUseCase and GetUserByEmailUseCase looks good, but we should verify all consumers are updated.

Also applies to: 26-27

✅ Verification successful

All consumers have been properly updated to use the new use cases

Based on the search results, there are no remaining references to the old GetUserUseCase. The new GetUserByIdUseCase and GetUserByEmailUseCase are properly:

  • Imported and provided in both auth.module.ts and users.module.ts
  • Injected and used correctly in UsersService
  • Fully tested in their respective spec files
  • Used appropriately in the resolver through the UsersService
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to GetUserUseCase
rg "GetUserUseCase" --type ts

# Search for constructor injections of the new use cases
rg "constructor.*GetUserBy(Id|Email)UseCase" --type ts

Length of output: 86


Script:

#!/bin/bash
# Let's try a broader search for any references to these use cases
rg -i "getuserby(id|email)" --type ts -A 2

# Also search for any files that might contain "getuser" to catch potential missed updates
rg -i "getuser" --type ts -A 2

# Let's also check the specific file mentioned in the review
cat libs/auth/interface-adapters/src/lib/auth.module.ts

Length of output: 19203

libs/users/domain/src/lib/users.repository.spec.ts (1)

19-21: LGTM: findByEmail implementation is clean and efficient

The implementation correctly uses Array.find() and handles the null case appropriately.

libs/users/application/src/lib/users.service.spec.ts (1)

Line range hint 32-52: LGTM! Well-structured tests for findById

The tests cover both successful and unsuccessful cases appropriately.

@zhumeisongsong zhumeisongsong merged commit b28e98a into main Dec 4, 2024
5 checks passed
@zhumeisongsong zhumeisongsong deleted the feature/get-user-by-email branch December 4, 2024 04:34
Copy link

github-actions bot commented Dec 4, 2024

🎉 This PR is included in version 1.11.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant