-
Notifications
You must be signed in to change notification settings - Fork 1
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
Conversation
WalkthroughThe changes introduce a new column Changes
Suggested reviewers
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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 newserverConfigId
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 UserDtoSince
UserDto
extendsCreateUserDto
, it will inherit the newserverConfigId
property. The Swagger documentation forUserDto
should be updated to reflect this change.Consider updating the Swagger documentation for
UserDto
to include the inheritedserverConfigId
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 constructorThe 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>
toPromise<{ 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:
- The import statements and function signature have been correctly updated.
- The new
serverConfig
variable is appropriately used within the function.- 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:
Error Handling: Consider adding more specific error types and messages. This could help in debugging and provide more informative responses to API consumers.
Swagger Documentation: If the addition of
userRepo
togetPatientDataUseCase
affects the structure of the response, update the Swagger documentation to reflect these changes.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 messageThere'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
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:
- Consider adding a brief comment explaining the purpose and usage of this new property.
- Update any relevant documentation (e.g., README, API docs) to reflect this addition.
- 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 theUserEntity
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 tableThis migration successfully adds a
server_config_id
column to theuser
table and establishes a foreign key relationship with theserver_config
table. These changes align well with the PR objective.Key points:
- The
server_config_id
is nullable, allowing users to exist without an associated server config.- If a server config is deleted, the corresponding user's
server_config_id
will be set to NULL.- 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 columnid
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: NewserverConfigId
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 forserverConfigId
.The validation schema has been properly updated to include the new
serverConfigId
property. The use ofz.string().optional()
correctly matches the optional string type defined in the constructor.
23-25
: LGTM: Getter method forserverConfigId
implemented correctly.The
getServerConfigId
method is implemented correctly, following the class's existing pattern for getter methods. It properly returns theserverConfigId
property with the correct return type ofstring | undefined
.
Line range hint
1-51
: Overall, the changes look good and achieve the PR objective.The addition of the
serverConfigId
property to theUserModel
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 objectivesThe addition of the
serverConfigId
property toCreateUserDto
(and by extension, toUserDto
) 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 constructorThe 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 objectThe 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 suggestionsThe 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:
mapEntityToModel
,mapModelToEntity
, andmapDtoToModel
functions have been correctly updated to include the new field.- A minor suggestion was made to improve consistency in the
mapDtoToModel
function by castingserverConfigId
to string in the UserModel constructor.- 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 consistencyThe
mapModelToDto
function has not been updated to include the newserver_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 themapModelToDto
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:
- 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'); }
Update the
CreateUserDto
interface to include theserverConfigId
field if it's not already present.Update the API documentation (Swagger) to reflect the changes in the request body and response structure.
Verify that the error handling in
handleApiValidationError
covers potential issues with the new data structure.Consider adding a comment explaining the purpose of
searchPatientUseCase
and why it's used instead of directly usingdto.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, likepatientData
, 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 theserver_config
model correctly establishes the one-to-many relationship with theuser
model. This change complements the relation added in theuser
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
andserver_config
models enhances the data structure while maintaining backward compatibility. However, there are some important considerations:
- Application logic may need to be updated to handle this new relationship.
- Existing data might require migration to populate the new fields.
- API endpoints and services interacting with users and server configurations may need adjustments.
To ensure a smooth integration of these changes:
- Update any affected application logic to utilize the new relationship.
- Create a data migration script to handle existing records if necessary.
- Review and update API documentation to reflect these changes.
- 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
: ImportingIUserRepository
is appropriateThe addition of
IUserRepository
is necessary for mocking the user repository in the tests.
31-31
: AddinggetServerConfigId
tomockUser
is appropriateIncluding
getServerConfigId
in themockUser
ensures that the user model has the necessary method for the tests.
47-50
: Update function call to includeuserRepo
The updated parameters in
getPatientDataUseCase
correctly includeuserRepo
, matching the new expected input structure.
63-66
: Update function call to includeuserRepo
This change mirrors the update in previous tests, ensuring consistency in passing
userRepo
togetPatientDataUseCase
.
77-80
: Update function call to includeuserRepo
Consistently including
userRepo
in the function call maintains the integrity of the test cases.
88-88
: Includeid
field in mock server configAdding 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 includeuserRepo
Passing
userRepo
togetPatientDataUseCase
ensures the test accurately reflects the function's requirements.
107-107
: Includeid
field in mock server configThis change is consistent with previous modifications and ensures that the mock data includes necessary identifiers.
112-115
: Update function call to includeuserRepo
The inclusion of
userRepo
in this test case maintains consistency across all tests after the function signature change.
There was a problem hiding this 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 mockingsearchPatientUseCase
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 mockingsearchPatientUseCase
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 improvementThe changes in this test file consistently update the mocks for
getUserProfile
andsearchPatientUseCase
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:
- Verify that the route handler in
src/app/api/v1/users/route.ts
correctly handles the new return value structure fromgetUserProfile
.- Update the assertions in the first test case to verify the correct processing of the new
searchPatientUseCase
return structure, especially theserverConfig
information.- 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
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 ingetUserProfile
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 ansrc/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.tsLength 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.tsLength of output: 468
There was a problem hiding this 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 thegetPatientDataUseCase
call is minimal and doesn't disrupt the existing structure or logic of the file. The code continues to demonstrate good practices such as:
- Use of dependency injection
- Separation of concerns
- Error handling
- Proper use of async/await
- 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
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 thegetPatientDataUseCase
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 newuserRepo
parameter.Verification successful
Verified! All calls to
getPatientDataUseCase
include theuserRepo
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 5Length of output: 3415
There was a problem hiding this 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:
- The function signature and return type have been appropriately updated.
- New imports and variable declarations support the added functionality.
- The mapping of server configurations ensures the correct model type is used.
Suggestions for improvement:
- Consider adding a type annotation for
serviceConfigs
for better readability.- 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
<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 thegetService
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:
- The parameter type change from
ServerConfigEntity
toServerConfigModel
reflects a shift towards using domain models.- Using
serverConfig.getEndpointUrl()
instead of directly accessingendpoint_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 toendpoint_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 thesearchPatientUseCase
function.
26-26
: LGTM: New serverConfig variable.The introduction of the
serverConfig
variable of typeServerConfigModel
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 thecontext
parameter ofgetPatientDataUseCase
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:
- Moving the server config mapping outside the conditional block enhances efficiency.
- The introduction of
throwMissingConfigError
centralizes error management.- The use of
fetchDataFromAllConfigs
andfetchDataFromUserConfig
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 theHapiFhirServiceFactory
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:
- Separation of concerns with new helper functions.
- Improved error handling and centralized error management.
- 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!
There was a problem hiding this 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 dataThe 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
topatientData
for improved clarity:- const data = { + const patientData = { resource: { id: expectedId, telecom: [{ system: 'email', value: email }], }, };
65-65
: Assertion updated, but server config check missingThe 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
<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 ServerConfigModelThe 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 expectationsThe changes to the mock setup are consistent with the new test expectations:
- The mock repository now returns an array with a single server config object.
- 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 improvementThe 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:
- The new import and data structures are appropriate for the updated test.
- The mock setup correctly provides the necessary data for both patient and server config.
- The assertion checks the patient data in the result.
Suggestions for improvement:
- Rename
data
topatientData
for clarity.- 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.
There was a problem hiding this 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
Summary by CodeRabbit
Release Notes
New Features
serverConfigId
properties across various models and data transfer objects.Bug Fixes
Documentation
Refactor