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 server config id to user #85

Merged
merged 8 commits into from
Sep 25, 2024

Conversation

jacob-khoza-symb
Copy link
Collaborator

@jacob-khoza-symb jacob-khoza-symb commented Sep 23, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new relationship between users and server configurations, allowing multiple users to be associated with a single server configuration.
    • Enhanced patient data retrieval to include server configuration details in the response.
    • Added optional serverConfigId properties across various models and data transfer objects.
  • Bug Fixes

    • Improved error handling for cases where users lack a server configuration ID.
  • Documentation

    • Updated test cases to reflect the new expected output structure for patient data retrieval.
  • Refactor

    • Improved the organization and readability of the patient data fetching logic.
    • Updated data mapping processes to consistently handle server configuration IDs across transformations.

Copy link

coderabbitai bot commented Sep 23, 2024

Walkthrough

The changes introduce a new column server_config_id to the user table, establishing a foreign key relationship with the server_config table. The prisma/schema.prisma file is updated to reflect these changes in the data models. Various application files are modified to accommodate the new user-server configuration relationship, including updates to data retrieval logic, DTOs, and mapping functions. Tests are also updated to ensure comprehensive coverage of the new functionality.

Changes

Files Change Summary
prisma/migrations/.../migration.sql, prisma/schema.prisma Added server_config_id column to user table with a foreign key constraint; updated models to reflect changes.
src/app/api/v1/users/[id]/ips/route.ts, src/app/api/v1/share-links/[id]/endpoints/[endpointId]/route.ts, src/app/api/v1/users/route.ts Modified data retrieval logic to include userRepo and updated how patient and server configuration IDs are handled.
src/domain/dtos/user.ts, src/domain/models/user.ts Added optional serverConfigId property to DTO and model; included methods for managing this property in the model.
src/entities/user.ts Introduced optional server_config_id property in UserEntity.
src/mappers/user-mapper.ts Updated mapping functions to handle server_config_id across entity, model, and DTO transformations.
src/usecases/patient/get-patient-data.test.ts, src/usecases/patient/get-patient-data.ts Updated test cases and use case logic to incorporate user repository and handle server configuration ID.
src/usecases/patient/search-patient-data.test.ts, src/usecases/patient/search-patient.ts Modified test and use case to return both patient data and server configuration, changing return types accordingly.

Suggested reviewers

  • BMartinos
  • yassinedorbozgithub
  • godchiSymbionix
  • amalessid

🐇 In the garden where data flows,
A new link blooms, as knowledge grows.
Server configs dance with user IDs,
Together they thrive, like bees and trees.
With each change, a hop towards the light,
In code we trust, our future is bright! 🌼


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

Outside diff range and nitpick comments (7)
src/domain/dtos/user.ts (2)

20-20: LGTM! Consider updating Swagger documentation.

The addition of the optional serverConfigId property is correct and aligns with the PR objective. Good job on making it optional to maintain backward compatibility.

Consider updating the Swagger documentation for CreateUserDto to include the new serverConfigId property. Here's a suggested addition:

/**
 * @swagger
 * components:
 *   schemas:
 *     CreateUser:
 *       type: object
 *       properties:
 *         patientId:
 *           type: string
 *           description: The patient's unique identifier in the external system.
 *           example: hWWNwskdGOnEdq0KIQ3S
 *         userId:
 *           type: string
 *           description: The user's unique identifier in the SSO system.
 *           example: 5AMl62z2XDmgrh2XsI2O
 *         serverConfigId:
 *           type: string
 *           description: The server configuration identifier.
 *           example: config123
 */

Line range hint 38-40: Update Swagger documentation for UserDto

Since UserDto extends CreateUserDto, it will inherit the new serverConfigId property. The Swagger documentation for UserDto should be updated to reflect this change.

Consider updating the Swagger documentation for UserDto to include the inherited serverConfigId property. Here's a suggested addition:

/**
 * @swagger
 * components:
 *   schemas:
 *     User:
 *       type: object
 *       properties:
 *         id:
 *           type: string
 *           description: The user unique identifier.
 *           example: hWWNwskdGOnEdq0KIQ3S
 *         patientId:
 *           type: string
 *           description: The patient's unique identifier in the external system.
 *           example: hWWNwskdGOnEdq0KIQ3S
 *         userId:
 *           type: string
 *           description: The user's unique identifier in the SSO system.
 *           example: 5AMl62z2XDmgrh2XsI2O
 *         serverConfigId:
 *           type: string
 *           description: The server configuration identifier.
 *           example: config123
 */
src/mappers/user-mapper.ts (1)

43-48: LGTM with a minor suggestion: Correctly added serverConfigId to UserModel constructor

The changes appropriately include the serverConfigId field when mapping from UserDto to UserModel. This is consistent with the PR objective and maintains the existing null-safety check.

For consistency with the other mapping functions, consider renaming the parameter in the UserModel constructor to server_config_id. This would make the interface of UserModel consistent across all mapping functions. Here's a suggested change:

 ? new UserModel(
     userDto.userId,
     userDto.patientId,
     userDto.id,
-    userDto.serverConfigId,
+    userDto.serverConfigId as string,
 )

This cast ensures type consistency with the other mapping functions while maintaining the camelCase naming in the DTO.

src/usecases/patient/search-patient.ts (2)

16-16: LGTM: Function signature updated appropriately.

The return type change from Promise<string> to Promise<{ patient: FhirPatient; serverConfig: ServerConfigEntity; }> is consistent with the function's new behavior. This provides more comprehensive information to the caller.

Consider updating the function's JSDoc comments (if any) to reflect the new return type and its significance.


Line range hint 1-54: Overall assessment: Well-implemented feature with a minor suggestion.

The changes to searchPatientUseCase function are well-implemented and consistent. The function now returns both the patient data and the corresponding server configuration, which enhances its usefulness. The modifications are backward-compatible in terms of function parameters.

Key points:

  1. The import statements and function signature have been correctly updated.
  2. The new serverConfig variable is appropriately used within the function.
  3. The return statement correctly provides the enhanced information.

Main suggestion:

  • Consider adding a check to ensure serverConfig is defined before returning, to handle cases where no matching configuration is found.

As this change exposes server configuration details alongside patient data, ensure that any sensitive information in ServerConfigEntity is properly sanitized before being returned to the client. Also, consider the impact of this change on any calling functions or services that may need to be updated to handle the new return type.

src/app/api/v1/users/[id]/ips/route.ts (1)

Line range hint 1-74: Consider these potential improvements:

  1. Error Handling: Consider adding more specific error types and messages. This could help in debugging and provide more informative responses to API consumers.

  2. Swagger Documentation: If the addition of userRepo to getPatientDataUseCase affects the structure of the response, update the Swagger documentation to reflect these changes.

  3. Logging: Consider adding more detailed logging throughout the function execution to aid in monitoring and debugging.

Here's an example of how you might enhance the error handling and logging:

try {
  // ... existing code ...
  logger.log(`Retrieved patient data for user: ${params.id}`);
  return NextResponse.json(result, { status: 200 });
} catch (error) {
  if (error instanceof UserNotFoundError) {
    logger.warn(`User not found: ${params.id}`);
    return NextResponse.json({ message: 'User not found' }, { status: 404 });
  } else if (error instanceof PatientDataNotFoundError) {
    logger.warn(`Patient data not found for user: ${params.id}`);
    return NextResponse.json({ message: 'Patient data not found' }, { status: 404 });
  }
  return handleApiValidationError(error, logger);
}

This suggestion adds more specific error handling and logging, which can improve debugging and provide more informative responses.

src/usecases/patient/get-patient-data.ts (1)

Line range hint 44-46: Correct typo in error message

There's a typo in the error message 'Unfullfilled request'; the correct spelling is 'Unfulfilled request'.

Apply this diff to correct the typo:

-throw new ExternalDataFetchError('Unfullfilled request');
+throw new ExternalDataFetchError('Unfulfilled request');
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 943445c and 1f3beb2.

Files selected for processing (12)
  • prisma/migrations/20240919145939_added_server_config_id_to_user/migration.sql (1 hunks)
  • prisma/schema.prisma (2 hunks)
  • src/app/api/v1/users/[id]/ips/route.ts (1 hunks)
  • src/app/api/v1/users/route.ts (1 hunks)
  • src/domain/dtos/user.ts (1 hunks)
  • src/domain/models/user.ts (1 hunks)
  • src/entities/user.ts (1 hunks)
  • src/mappers/user-mapper.ts (3 hunks)
  • src/usecases/patient/get-patient-data.test.ts (7 hunks)
  • src/usecases/patient/get-patient-data.ts (2 hunks)
  • src/usecases/patient/search-patient-data.test.ts (1 hunks)
  • src/usecases/patient/search-patient.ts (3 hunks)
Additional comments not posted (29)
src/entities/user.ts (1)

6-6: Approved: New property added successfully. Consider adding documentation and verifying impacts.

The addition of the server_config_id property looks good. It's correctly typed as an optional string and follows the existing naming convention.

To improve clarity and maintainability:

  1. Consider adding a brief comment explaining the purpose and usage of this new property.
  2. Update any relevant documentation (e.g., README, API docs) to reflect this addition.
  3. Verify if any other parts of the codebase need updates to accommodate this new property.

To help identify potential areas that might need updates, you can run the following script:

This script will help identify files that might need to be updated to handle the new server_config_id property.

Verification successful

[/run_scripts]


Verified: Addition of server_config_id property is consistently integrated across the codebase.

The server_config_id property has been successfully added to the UserEntity class and is being utilized appropriately in the following files:

  • src/mappers/user-mapper.ts
  • src/mappers/shlink-endpoint-mapper.ts

No issues were found during the verification process.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of UserEntity that might need updates

# Search for UserEntity usages
echo "UserEntity usages:"
rg --type typescript "UserEntity" --glob '!src/entities/user.ts'

# Search for user_id usages (as a proxy for UserEntity property access)
echo "\nPotential UserEntity property accesses:"
rg --type typescript "\.user_id" --glob '!src/entities/user.ts'

Length of output: 340


Script:

#!/bin/bash
# Description: Find usages of UserEntity that might need updates

# Search for UserEntity usages excluding the user.ts file
echo "UserEntity usages:"
rg --type ts "UserEntity" --glob '!src/entities/user.ts'

# Search for server_config_id property accesses excluding the user.ts file
echo "\nPotential UserEntity property accesses:"
rg --type ts "\.server_config_id" --glob '!src/entities/user.ts'

Length of output: 3050

prisma/migrations/20240919145939_added_server_config_id_to_user/migration.sql (3)

1-5: Summary: Server Config ID successfully added to User table

This migration successfully adds a server_config_id column to the user table and establishes a foreign key relationship with the server_config table. These changes align well with the PR objective.

Key points:

  1. The server_config_id is nullable, allowing users to exist without an associated server config.
  2. If a server config is deleted, the corresponding user's server_config_id will be set to NULL.
  3. Updates to a server config's ID will be cascaded to the user table.

These changes provide flexibility in managing user-server config relationships while maintaining data integrity.


5-5: LGTM! Verify referenced table and column.

The foreign key constraint is well-defined. The constraint name follows conventions, and the ON DELETE and ON UPDATE behaviors are appropriate for maintaining referential integrity.

To ensure the referenced table and column exist, run the following script:

Verification successful

Verification Successful!

The referenced table server_config and column id exist.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the "server_config" table and its "id" column
# Expected result: Should show the CREATE TABLE statement for "server_config" including the "id" column

# Test: Search for the CREATE TABLE statement of "server_config"
echo "Searching for server_config table definition:"
rg --type sql -A 10 'CREATE TABLE.*"server_config"'

Length of output: 1163


2-2: LGTM! Consider column nullability.

The addition of the "server_config_id" column to the "user" table looks good. The column name is appropriate, and the TEXT type is suitable for storing IDs.

However, it's worth noting that the column is nullable by default. If this is intentional, it's fine. If not, you might want to add a NOT NULL constraint. To verify the current schema, you can run:

Verification successful

LGTM! The "server_config_id" column is being added as nullable.

The addition of the "server_config_id" column to the "user" table has been verified. Currently, the column is nullable. If a NOT NULL constraint is required, consider updating the migration to enforce non-nullability.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the schema of the "user" table
# Expected result: Should show the "server_config_id" column and its properties

# Test: Describe the "user" table schema
echo "Describing user table schema:"
rg --type sql -A 10 'CREATE TABLE.*"user"'

Length of output: 960

src/domain/models/user.ts (4)

10-10: LGTM: New serverConfigId property added correctly.

The serverConfigId property has been added to the constructor with the correct type (string) and visibility (private). It's also properly marked as optional, which maintains backward compatibility with existing code.


17-17: LGTM: Validation schema updated correctly for serverConfigId.

The validation schema has been properly updated to include the new serverConfigId property. The use of z.string().optional() correctly matches the optional string type defined in the constructor.


23-25: LGTM: Getter method for serverConfigId implemented correctly.

The getServerConfigId method is implemented correctly, following the class's existing pattern for getter methods. It properly returns the serverConfigId property with the correct return type of string | undefined.


Line range hint 1-51: Overall, the changes look good and achieve the PR objective.

The addition of the serverConfigId property to the UserModel class has been implemented correctly, including appropriate getter and setter methods. The validation schema has been updated to match the new property.

A minor suggestion was made to improve the setServerConfigId method for better validation and consistency. Consider implementing this suggestion to enhance the robustness of the code.

These changes successfully add the server config ID to the user model as intended by the PR objective.

src/domain/dtos/user.ts (1)

Line range hint 1-40: Changes align well with PR objectives

The addition of the serverConfigId property to CreateUserDto (and by extension, to UserDto) is consistent with the PR objective of adding server config id to user. The implementation as an optional property is a good choice for maintaining backward compatibility.

src/mappers/user-mapper.ts (4)

9-14: LGTM: Correctly added server_config_id to UserModel constructor

The changes appropriately include the server_config_id field when mapping from UserEntity to UserModel. This is consistent with the PR objective and maintains the existing null-safety check.


26-26: LGTM: Correctly added server_config_id to the entity object

The changes appropriately include the server_config_id field when mapping from UserModel to UserEntity. This is consistent with the PR objective, maintains the existing null-safety check, and follows the correct naming convention (snake_case) for entity fields.


Line range hint 1-51: Summary of changes and suggestions

The changes to add server_config_id to the user mapping functions are generally well-implemented and consistent with the PR objective. Here's a summary of the review:

  1. mapEntityToModel, mapModelToEntity, and mapDtoToModel functions have been correctly updated to include the new field.
  2. A minor suggestion was made to improve consistency in the mapDtoToModel function by casting serverConfigId to string in the UserModel constructor.
  3. The mapModelToDto function was not updated. A verification step was suggested to determine if this function should also include the new field for consistency.

Overall, the changes look good, but please consider the suggestions to ensure full consistency across all mapping functions.


Line range hint 30-38: Consider adding serverConfigId to the DTO for consistency

The mapModelToDto function has not been updated to include the new server_config_id field. While this might be intentional if the DTO doesn't require this field, it's worth considering adding it for consistency with the other mapping functions and to ensure no data loss during transformations.

If the DTO should include the serverConfigId, consider updating the function as follows:

 export const mapModelToDto = (userModel: UserModel): UserDto | undefined => {
   return userModel
     ? {
         id: userModel.getId(),
         patientId: userModel.getPatientId(),
         userId: userModel.getUserId(),
+        serverConfigId: userModel.getServerConfigId(),
       }
     : undefined;
 };

To verify if this change is necessary, please check the UserDto interface:

If the UserDto interface includes serverConfigId, please update the mapModelToDto function accordingly.

src/usecases/patient/search-patient.ts (2)

3-3: LGTM: Import statement added correctly.

The new import for ServerConfigEntity is consistent with the changes made in the function and follows the existing import style.


46-46: LGTM: Return statement updated correctly.

The modified return statement now includes both the patient resource and the server configuration, which aligns perfectly with the updated function signature. This change provides more comprehensive information to the caller, enhancing the usefulness of the function.

src/app/api/v1/users/[id]/ips/route.ts (1)

Line range hint 39-74: LGTM: Robust implementation of the GET function.

The GET function implementation is well-structured and follows best practices:

  • It uses unstable_noStore() to ensure fresh data is always fetched, which is crucial for medical information.
  • User validation is performed before data retrieval, enhancing security.
  • The error handling is comprehensive, using a custom handler for consistency.
  • The function follows a logical flow: validate user, get user data, retrieve patient data.
src/app/api/v1/users/route.ts (1)

55-60: Improved data retrieval process, but consider additional safeguards and updates.

The changes improve the data retrieval process by fetching both patient and server configuration data in one step. This is a good optimization. However, there are a few points to consider:

  1. Add null checks for the new data structure to prevent potential runtime errors:
if (!data?.patient?.id || !data?.serverConfig?.id) {
  throw new Error('Invalid patient or server configuration data');
}
  1. Update the CreateUserDto interface to include the serverConfigId field if it's not already present.

  2. Update the API documentation (Swagger) to reflect the changes in the request body and response structure.

  3. Verify that the error handling in handleApiValidationError covers potential issues with the new data structure.

  4. Consider adding a comment explaining the purpose of searchPatientUseCase and why it's used instead of directly using dto.patientId.

To ensure the CreateUserDto interface is up-to-date, run the following script:

To verify the API documentation is consistent with the changes:

src/usecases/patient/search-patient-data.test.ts (1)

39-63: LGTM! Consider improving variable naming for clarity.

The changes to the test case accurately reflect the updated behavior of the searchPatientUseCase function. The test now correctly checks for both patient data and server configuration in the result.

Consider renaming the data variable to something more specific, like patientData, to improve clarity:

-    const data = {
+    const patientData = {
       resource: {
         id: expectedId,
         telecom: [{ system: 'email', value: email }],
       },
     };

     // ... (other code)

-    expect(result).toEqual({ patient: { ...data.resource }, serverConfig });
+    expect(result).toEqual({ patient: { ...patientData.resource }, serverConfig });

This change would make it immediately clear that the variable represents patient data.

To ensure these changes are reflected in the actual implementation, please run the following script:

This will help us confirm that the implementation matches the updated test expectations.

Verification successful

Verified! The searchPatientUseCase function implementation correctly returns both patient data and server configuration, and the test case accurately verifies this behavior.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the searchPatientUseCase function returns both patient data and server config

# Test: Search for the searchPatientUseCase function implementation
rg --type typescript -A 10 'export const searchPatientUseCase'

Length of output: 99


Script:

#!/bin/bash
# Description: Verify that the searchPatientUseCase function returns both patient data and server config

# Test: Search for the searchPatientUseCase function implementation
rg --type ts -A 10 'export const searchPatientUseCase'

Length of output: 871


Script:

#!/bin/bash
# Description: Retrieve the complete implementation of the searchPatientUseCase function

# Search for the searchPatientUseCase function and display 30 lines after the match to capture the full implementation
rg --type ts -A 30 'export const searchPatientUseCase'

Length of output: 2154


Script:

#!/bin/bash
# Description: Retrieve the complete implementation of the searchPatientUseCase function

# Search for the searchPatientUseCase function and display up to 60 lines after the match to capture the full implementation
rg --type ts -A 60 'export const searchPatientUseCase'

Length of output: 2849

prisma/schema.prisma (2)

89-89: LGTM! Relation correctly established.

The addition of the users field in the server_config model correctly establishes the one-to-many relationship with the user model. This change complements the relation added in the user model and allows for multiple users to be associated with a single server configuration.


64-69: Consider the broader impact of these changes.

The introduction of the relationship between user and server_config models enhances the data structure while maintaining backward compatibility. However, there are some important considerations:

  1. Application logic may need to be updated to handle this new relationship.
  2. Existing data might require migration to populate the new fields.
  3. API endpoints and services interacting with users and server configurations may need adjustments.

To ensure a smooth integration of these changes:

  1. Update any affected application logic to utilize the new relationship.
  2. Create a data migration script to handle existing records if necessary.
  3. Review and update API documentation to reflect these changes.
  4. Consider adding integration tests to verify the correct handling of the new relationship.

To help identify potential areas that might need updates, you can run the following script:

This script will help identify files that might need to be updated to accommodate the new relationship between users and server configurations.

Also applies to: 89-89

src/usecases/patient/get-patient-data.test.ts (9)

3-3: Importing IUserRepository is appropriate

The addition of IUserRepository is necessary for mocking the user repository in the tests.


31-31: Adding getServerConfigId to mockUser is appropriate

Including getServerConfigId in the mockUser ensures that the user model has the necessary method for the tests.


47-50: Update function call to include userRepo

The updated parameters in getPatientDataUseCase correctly include userRepo, matching the new expected input structure.


63-66: Update function call to include userRepo

This change mirrors the update in previous tests, ensuring consistency in passing userRepo to getPatientDataUseCase.


77-80: Update function call to include userRepo

Consistently including userRepo in the function call maintains the integrity of the test cases.


88-88: Include id field in mock server config

Adding the id field to the mock server configuration aligns with the expected data structure and supports the retrieval of the correct configuration.


93-93: Update function call to include userRepo

Passing userRepo to getPatientDataUseCase ensures the test accurately reflects the function's requirements.


107-107: Include id field in mock server config

This change is consistent with previous modifications and ensures that the mock data includes necessary identifiers.


112-115: Update function call to include userRepo

The inclusion of userRepo in this test case maintains consistency across all tests after the function signature change.

src/domain/models/user.ts Show resolved Hide resolved
src/usecases/patient/search-patient.ts Outdated Show resolved Hide resolved
src/app/api/v1/users/[id]/ips/route.ts Show resolved Hide resolved
prisma/schema.prisma Show resolved Hide resolved
src/usecases/patient/get-patient-data.ts Outdated Show resolved Hide resolved
src/usecases/patient/get-patient-data.ts Outdated Show resolved Hide resolved
src/usecases/patient/get-patient-data.ts Outdated Show resolved Hide resolved
src/usecases/patient/get-patient-data.ts Outdated Show resolved Hide resolved
src/usecases/patient/get-patient-data.test.ts Show resolved Hide resolved
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: 1

Outside diff range and nitpick comments (3)
src/app/api/v1/users/route.test.ts (3)

94-97: Approve consistent mock, but consider its necessity in this test case.

The searchPatientUseCase mock is consistent with the previous test case, which is good for maintaining test reliability.

Given that this test case focuses on validation errors from addUserUseCase, consider if mocking searchPatientUseCase is necessary here. If it's not used in the validation logic, you might be able to remove this mock for this specific test case to keep it focused on its primary concern.


119-122: Approve consistent mock, but reconsider its necessity in this test case.

The searchPatientUseCase mock maintains consistency with the previous test cases.

As this test case focuses on handling unexpected errors from addUserUseCase, consider if mocking searchPatientUseCase is necessary here. If it's not used in the error handling logic, you might be able to remove this mock for this specific test case to keep it focused on its primary concern of error handling.


Line range hint 1-141: Summary of changes and suggestions for improvement

The changes in this test file consistently update the mocks for getUserProfile and searchPatientUseCase to return more detailed information, including server configuration. These changes align with the AI-generated summary and suggest a broader refactoring of the user creation process.

To improve the effectiveness of these tests:

  1. Verify that the route handler in src/app/api/v1/users/route.ts correctly handles the new return value structure from getUserProfile.
  2. Update the assertions in the first test case to verify the correct processing of the new searchPatientUseCase return structure, especially the serverConfig information.
  3. Reconsider the necessity of mocking searchPatientUseCase in the validation error and unexpected error test cases, as they might not be directly relevant to these specific scenarios.

These refinements will ensure that the tests remain focused on their primary concerns while accurately reflecting the changes in the underlying implementation.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1f3beb2 and 1af5bc2.

Files selected for processing (2)
  • src/app/api/v1/users/route.test.ts (4 hunks)
  • src/app/api/v1/users/route.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/app/api/v1/users/route.ts
Additional comments not posted (1)
src/app/api/v1/users/route.test.ts (1)

65-65: Approve change in getUserProfile mock, but verify route handler.

The mock for getUserProfile now returns an object with an email property, which is more realistic. This change is consistent and aligns with the summary.

Please verify that the route handler in src/app/api/v1/users/route.ts correctly handles this new return value structure. Run the following script to check the usage:

Verification successful

Verified change in getUserProfile mock.

The mock for getUserProfile correctly returns an object with an email property, and the route handler in src/app/api/v1/users/route.ts appropriately destructures and utilizes this property. No further changes are needed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how getUserProfile is used in the route handler

# Test: Search for getUserProfile usage in the route file
rg --type typescript -A 5 'getUserProfile' src/app/api/v1/users/route.ts

Length of output: 107


Script:

#!/bin/bash
# Description: Check how getUserProfile is used in the route handler with correct file type

# Test: Search for getUserProfile usage in the route file using correct type
rg --type ts -A 5 'getUserProfile' src/app/api/v1/users/route.ts

Length of output: 468

src/app/api/v1/users/route.test.ts Outdated Show resolved Hide resolved
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: 0

Outside diff range and nitpick comments (1)
src/app/api/v1/share-links/[id]/endpoints/[endpointId]/route.ts (1)

Line range hint 1-114: Overall, the changes look good and maintain code quality.

The modification to include userRepo in the getPatientDataUseCase call is minimal and doesn't disrupt the existing structure or logic of the file. The code continues to demonstrate good practices such as:

  1. Use of dependency injection
  2. Separation of concerns
  3. Error handling
  4. Proper use of async/await
  5. Swagger documentation for the API endpoint

The change aligns well with the existing code structure and doesn't introduce any apparent issues.

Consider adding unit tests for this route handler if they don't already exist, especially to cover the new behavior with the added userRepo parameter.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1af5bc2 and 2267aad.

Files selected for processing (1)
  • src/app/api/v1/share-links/[id]/endpoints/[endpointId]/route.ts (1 hunks)
Additional comments not posted (1)
src/app/api/v1/share-links/[id]/endpoints/[endpointId]/route.ts (1)

104-104: LGTM! Verify consistency across the codebase.

The addition of userRepo to the getPatientDataUseCase function call is a logical change that aligns with the function's purpose of retrieving patient data. It allows the use case to access user-specific information if needed.

To ensure consistency, please run the following script to verify that all calls to getPatientDataUseCase have been updated with the new parameter:

Also, please confirm that the getPatientDataUseCase implementation has been updated to handle the new userRepo parameter.

Verification successful

Verified! All calls to getPatientDataUseCase include the userRepo parameter consistently across the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `getPatientDataUseCase` include the `userRepo` parameter.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type typescript -A 5 $'getPatientDataUseCase\('

Length of output: 88


Script:

#!/bin/bash
# Description: Verify all function calls to `getPatientDataUseCase` include the `userRepo` parameter.

# Search within .ts and .tsx files for `getPatientDataUseCase(` and display context lines.
rg 'getPatientDataUseCase\(' -g '*.ts' -g '*.tsx' -A 5

Length of output: 3415

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

Outside diff range and nitpick comments (2)
src/usecases/patient/search-patient.ts (2)

17-20: LGTM: Updated function signature and return type.

The changes to the function signature and return type accurately reflect the new functionality of returning both the patient and server configuration. The mapping of serviceConfigs ensures that the correct model type is used.

Consider adding a type annotation for serviceConfigs for better readability:

const serviceConfigs: ServerConfigModel[] = (await context.repo.findMany({})).map((x) =>
  mapEntityToModel(x)
);

Line range hint 1-58: Overall, the changes look good with some minor suggestions for improvement.

The modifications to searchPatientUseCase successfully implement the new functionality of returning both the patient resource and the server configuration. The changes are consistent and well-integrated into the existing code structure.

Key points:

  1. The function signature and return type have been appropriately updated.
  2. New imports and variable declarations support the added functionality.
  3. The mapping of server configurations ensures the correct model type is used.

Suggestions for improvement:

  1. Consider adding a type annotation for serviceConfigs for better readability.
  2. Implement additional error handling to ensure serverConfig is defined before returning.

These improvements will enhance the robustness and maintainability of the code.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2267aad and 1bf1790.

<details>
Files selected for processing (4)
  • src/services/hapi-fhir-factory.ts (1 hunks)
  • src/usecases/patient/get-patient-data.ts (2 hunks)
  • src/usecases/patient/search-patient-data.test.ts (2 hunks)
  • src/usecases/patient/search-patient.ts (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/usecases/patient/search-patient-data.test.ts
Additional comments not posted (10)
src/services/hapi-fhir-factory.ts (2)

3-3: LGTM: Import statement updated correctly.

The import of ServerConfigModel is consistent with the changes in the getService method signature. This update ensures that the correct type is available for use in the class.


6-7: LGTM: Method signature and implementation updated correctly.

The changes to the getService method are well-implemented:

  1. The parameter type change from ServerConfigEntity to ServerConfigModel reflects a shift towards using domain models.
  2. Using serverConfig.getEndpointUrl() instead of directly accessing endpoint_url improves encapsulation.

These updates align with good software design principles. However, it's important to ensure that these changes are consistently applied throughout the codebase.

To verify the impact of these changes, please run the following script:

This script will help identify any areas of the codebase that might need updates to maintain consistency with these changes.

Verification successful

Verified: No remaining usages of ServerConfigEntity or direct access to endpoint_url found. Changes are consistent across the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usages of ServerConfigEntity and direct access to endpoint_url

echo "Checking for remaining usages of ServerConfigEntity:"
rg --type typescript "ServerConfigEntity"

echo "\nChecking for direct access to endpoint_url:"
rg --type typescript "\.endpoint_url"

echo "\nChecking for usages of getEndpointUrl method:"
rg --type typescript "\.getEndpointUrl\(\)"

Length of output: 553


Script:

#!/bin/bash
# Description: Check for any remaining usages of ServerConfigEntity, direct access to endpoint_url, and usages of getEndpointUrl method using ast-grep

echo "Checking for remaining usages of ServerConfigEntity:"
ast-grep --lang typescript --pattern $'$_ServerConfigEntity$$' src/

echo "\nChecking for direct access to endpoint_url:"
ast-grep --lang typescript --pattern $'$_$.endpoint_url' src/

echo "\nChecking for usages of getEndpointUrl method:"
ast-grep --lang typescript --pattern $'$_$.getEndpointUrl()' src/

Length of output: 519

src/usecases/patient/search-patient.ts (3)

11-11: LGTM: New import for server config mapping.

The addition of mapEntityToModel import is appropriate for the new functionality of handling server configurations in the searchPatientUseCase function.


26-26: LGTM: New serverConfig variable.

The introduction of the serverConfig variable of type ServerConfigModel is appropriate for storing the current server configuration being processed in the loop.


49-49: LGTM with a suggestion: Consider additional error handling for serverConfig.

The updated return statement correctly includes both the patient resource and the server configuration, aligning with the new function signature.

However, there's a potential issue: serverConfig might be undefined if no matching configuration is found in the loop. To address this, consider adding a check before the return statement:

if (!serverConfig) {
  throw new ExternalDataFetchError('No matching server configuration found.', 404);
}
return { patient: result.entry[0].resource, serverConfig };

This ensures that we always return a valid server configuration or throw an appropriate error.

To verify the necessity of this check, let's analyze the usage of serverConfig:

src/usecases/patient/get-patient-data.ts (5)

1-1: LGTM: Import and function signature changes are appropriate.

The addition of IUserRepository and its inclusion in the context parameter of getPatientDataUseCase aligns well with the new functionality to update the user's server config ID. These changes improve the use case's capabilities and maintain good dependency injection practices.

Also applies to: 4-6, 8-8, 12-12


15-17: Improved code structure and error handling.

The changes in this section significantly improve the code structure and readability:

  1. Moving the server config mapping outside the conditional block enhances efficiency.
  2. The introduction of throwMissingConfigError centralizes error management.
  3. The use of fetchDataFromAllConfigs and fetchDataFromUserConfig improves code organization.

These changes effectively address the previous review comment about refactoring nested try-catch blocks and improving readability.

Also applies to: 20-20, 23-29


42-44: LGTM: Centralized error handling for missing configurations.

The throwMissingConfigError function effectively centralizes error handling for missing configurations, improving consistency and addressing a suggestion from a previous review.


46-53: LGTM: Well-encapsulated data fetching logic.

The getData function effectively encapsulates the logic for fetching patient data from the FHIR service. This improves code organization, enhances reusability, and follows good practices by using the HapiFhirServiceFactory for dependency management.


Line range hint 1-86: Overall code structure and modularity greatly improved.

The changes in this pull request have significantly enhanced the code structure, modularity, and error handling of the getPatientDataUseCase. Key improvements include:

  1. Separation of concerns with new helper functions.
  2. Improved error handling and centralized error management.
  3. Better organization of the main function flow.

These changes address most of the concerns raised in previous reviews and make the code more maintainable and readable. While there are a couple of minor suggestions for further improvement in the individual function reviews, the overall direction and implementation are solid.

Great job on the refactoring!

src/usecases/patient/get-patient-data.ts Show resolved Hide resolved
src/usecases/patient/get-patient-data.ts Show resolved Hide resolved
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: 0

Outside diff range and nitpick comments (2)
src/usecases/patient/search-patient-data.test.ts (2)

40-50: LGTM: Test case updated to include server config data

The test description and setup have been appropriately updated to reflect the new expected output, which now includes both patient and server configuration data. This is consistent with the changes described in the AI summary.

Consider renaming data to patientData for improved clarity:

-    const data = {
+    const patientData = {
       resource: {
         id: expectedId,
         telecom: [{ system: 'email', value: email }],
       },
     };

65-65: Assertion updated, but server config check missing

The assertion has been correctly updated to check the patient data in the new result structure. However, the test is not verifying the server config part of the result.

Consider adding an assertion for the server config data to ensure the function is returning both patient and server config data as expected:

     expect(result.patient).toEqual({ ...data.resource });
+    expect(result.serverConfig).toEqual(expectedConfig);
     expect(mockService.searchPatient).toHaveBeenCalledWith(patientId);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1bf1790 and f93c72d.

<details>
Files selected for processing (5)
  • src/app/api/v1/users/route.test.ts (5 hunks)
  • src/app/api/v1/users/route.ts (1 hunks)
  • src/services/hapi-fhir-factory.ts (1 hunks)
  • src/usecases/patient/search-patient-data.test.ts (2 hunks)
  • src/usecases/patient/search-patient.ts (3 hunks)
Files skipped from review as they are similar to previous changes (4)
  • src/app/api/v1/users/route.test.ts
  • src/app/api/v1/users/route.ts
  • src/services/hapi-fhir-factory.ts
  • src/usecases/patient/search-patient.ts
Additional comments not posted (3)
src/usecases/patient/search-patient-data.test.ts (3)

2-2: LGTM: Import added for ServerConfigModel

The addition of the ServerConfigModel import is consistent with the changes in the test case that now includes server configuration data.


53-57: LGTM: Mock setup updated to match new expectations

The changes to the mock setup are consistent with the new test expectations:

  1. The mock repository now returns an array with a single server config object.
  2. The mock service's return structure has been simplified to directly return the patient data in the expected format.

These changes align well with the updated test case and the new output structure of the searchPatientUseCase function.


Line range hint 1-94: Summary: Test updated successfully with minor suggestions for improvement

The changes to this test file successfully reflect the new structure of the searchPatientUseCase function's output, which now includes both patient and server configuration data. The test description, mock setup, and assertions have been updated accordingly.

Key points:

  1. The new import and data structures are appropriate for the updated test.
  2. The mock setup correctly provides the necessary data for both patient and server config.
  3. The assertion checks the patient data in the result.

Suggestions for improvement:

  1. Rename data to patientData for clarity.
  2. Add an assertion to verify the server config data in the result.

These changes will enhance the test's readability and ensure it fully covers the new function output structure.

Copy link
Collaborator

@godchiSymbionix godchiSymbionix left a comment

Choose a reason for hiding this comment

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

Looks good overall from my end

@jacob-khoza-symb jacob-khoza-symb merged commit 766e869 into main Sep 25, 2024
3 checks passed
@jacob-khoza-symb jacob-khoza-symb deleted the feat/add-server-config-id-to-user branch September 25, 2024 11:30
@coderabbitai coderabbitai bot mentioned this pull request Sep 27, 2024
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