-
Notifications
You must be signed in to change notification settings - Fork 577
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
[Fix] Integer Storage for ActorTypeEnum in Database #8419
Conversation
WalkthroughThe pull request introduces several key changes across multiple files. The Changes
Possibly related PRs
Poem
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: 6
🧹 Outside diff range and nitpick comments (6)
packages/core/src/shared/pipes/use-validation.pipe.ts (2)
13-15
: LGTM: Well-implemented custom validation pipe decorator.The
UseValidationPipe
function is correctly implemented, providing a convenient way to apply custom validation pipes in NestJS applications. The use of the nullish coalescing operator ensures proper handling of undefined options.Consider adding explicit return type annotation for improved type safety:
-export function UseValidationPipe(options?: Partial<ValidationPipeOptions>) { +export function UseValidationPipe(options?: Partial<ValidationPipeOptions>): MethodDecorator & ClassDecorator { return UsePipes(new ValidationPipe(options ?? {})); }
1-15
: Overall assessment: Excellent addition to enhance validation mechanisms.This new file introduces a well-implemented and thoroughly documented custom decorator
UseValidationPipe
. It aligns with the PR objectives by simplifying the application of validation pipes in the project. The code is clean, follows good practices, and enhances the developer experience when working with validation in NestJS applications.Consider adding unit tests for this utility function to ensure its behavior remains consistent across future changes.
packages/core/src/shared/pipes/actor-type-transform.pipe.ts (2)
12-21
: LGTM: Well-implementedto
method with clear documentation.The
to
method is correctly implemented:
- It properly converts
ActorTypeEnum
to the corresponding integer.- The logging statement aids in debugging.
- The multi-line comment clearly explains the method's purpose and parameters.
Consider adding error handling for unexpected enum values:
to(value: ActorTypeEnum): number { this.logger.debug(`ActorTypeTransformerPipe: converting ${value} to integer`); - return value === ActorTypeEnum.User ? 1 : 0; // 1 for 'User', 0 for 'System' (default) + switch (value) { + case ActorTypeEnum.User: + return 1; + case ActorTypeEnum.System: + return 0; + default: + this.logger.error(`Unexpected ActorTypeEnum value: ${value}`); + throw new Error(`Unexpected ActorTypeEnum value: ${value}`); + } }This change would make the method more robust by explicitly handling all possible cases and throwing an error for unexpected values.
23-33
: LGTM: Well-implementedfrom
method with clear documentation.The
from
method is correctly implemented:
- It properly converts the integer to the corresponding
ActorTypeEnum
.- The logging statement aids in debugging.
- The multi-line comment clearly explains the method's purpose and parameters.
Consider adding error handling for unexpected integer values:
from(value: number): ActorTypeEnum { this.logger.debug(`ActorTypeTransformerPipe: converting ${value} to enum`); - return value === 1 ? ActorTypeEnum.User : ActorTypeEnum.System; + switch (value) { + case 1: + return ActorTypeEnum.User; + case 0: + return ActorTypeEnum.System; + default: + this.logger.error(`Unexpected integer value: ${value}`); + throw new Error(`Unexpected integer value: ${value}`); + } }This change would make the method more robust by explicitly handling all possible cases and throwing an error for unexpected values.
packages/core/src/activity-log/dto/get-activity-logs.dto.ts (1)
18-18
: LGTM: Include actorType in PickType, but consider documentation updateThe addition of 'actorType' to the
PickType
forActivityLog
is consistent with the PR objective. This change allows filtering byactorType
in requests, which can be beneficial for more granular querying.Consider updating the API documentation to reflect this change, as it might affect API consumers who weren't previously expecting the
actorType
field in responses.packages/core/src/activity-log/activity-log.entity.ts (1)
37-42
: LGTM: Improved actorType property with integer storage and transformer.The changes to the
actorType
property effectively address the PR objective of implementing integer storage for ActorTypeEnum. The use ofActorTypeTransformerPipe
allows for seamless conversion between the enum and its integer representation, which is an excellent approach.A minor suggestion for improvement:
Consider updating the comment to be more specific about the enum values and their corresponding integer representations. For example:
- actorType?: ActorTypeEnum; // Will be stored as 0 or 1 in DB + actorType?: ActorTypeEnum; // Will be stored as integers in DB (e.g., SYSTEM = 0, USER = 1)This provides more precise information about the storage format and enum mapping.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (10)
- packages/contracts/src/base-entity.model.ts (1 hunks)
- packages/core/src/activity-log/activity-log.controller.ts (2 hunks)
- packages/core/src/activity-log/activity-log.entity.ts (2 hunks)
- packages/core/src/activity-log/activity-log.service.ts (3 hunks)
- packages/core/src/activity-log/dto/get-activity-logs.dto.ts (2 hunks)
- packages/core/src/comment/comment.entity.ts (2 hunks)
- packages/core/src/shared/pipes/actor-type-transform.pipe.ts (1 hunks)
- packages/core/src/shared/pipes/index.ts (1 hunks)
- packages/core/src/shared/pipes/use-validation-pipe.pipe.ts (0 hunks)
- packages/core/src/shared/pipes/use-validation.pipe.ts (1 hunks)
💤 Files with no reviewable changes (1)
- packages/core/src/shared/pipes/use-validation-pipe.pipe.ts
🧰 Additional context used
🔇 Additional comments (21)
packages/core/src/shared/pipes/index.ts (6)
1-1
: LGTM: New export added for abstract-validation.pipeThis new export aligns with the changes mentioned in the AI summary. It's a good addition that makes the abstract validation pipe available for use in other parts of the application.
2-2
: LGTM: New export added for actor-type-transform.pipeThis new export is in line with the PR objective of fixing integer storage for ActorTypeEnum. The actor-type-transform pipe will likely play a crucial role in handling the conversion between different representations of actor types.
6-6
: Verify the status of parse-json.pipe exportThe AI summary mentions that the export for 'parse-json.pipe' was both removed and added. However, it appears in the current code. Could you please clarify if this export was intentionally kept or if it was removed and then re-added? This will help ensure consistency between the changes and the documentation.
7-7
: Verify the correct name of the use-validation pipeThe AI summary mentions an export for 'use-validation-pipe.pipe', but the code shows 'use-validation.pipe'. Could you please confirm that this is the correct name for the pipe? If it's intentional, we might need to update the PR description or comments to reflect the correct naming.
8-8
: Verify the status of uuid-validation.pipe exportThe AI summary indicates that the export for 'uuid-validation.pipe' was both removed and added. However, it appears in the current code. Could you please clarify if this export was intentionally kept or if it was removed and then re-added? This clarification will help ensure consistency between the changes and the documentation.
1-8
: Summary of changes and points for clarificationThe changes to this file generally align with the PR objective of fixing integer storage for ActorTypeEnum. The addition of the
actor-type-transform.pipe
export is particularly relevant to this goal. However, there are a few points that require clarification:
- The status of the
parse-json.pipe
anduuid-validation.pipe
exports, which the AI summary indicated were both removed and added.- The correct name of the
use-validation.pipe
export, as there's a slight discrepancy between the code and the AI summary.Once these points are clarified, we can ensure that the changes are fully consistent with the PR objectives and documentation.
packages/core/src/shared/pipes/use-validation.pipe.ts (2)
1-1
: LGTM: Imports are correct and necessary.The imports from '@nestjs/common' are appropriate for the implementation of the custom validation pipe.
3-12
: LGTM: Well-documented function with comprehensive JSDoc comments.The JSDoc comments provide clear and detailed information about the
UseValidationPipe
function, including its purpose, functionality, parameters, and return value.packages/core/src/activity-log/activity-log.controller.ts (1)
23-24
: LGTM! Consider verifying DTO handling in the service layer.The addition of
{ transform: true }
to@UseValidationPipe
is a good improvement. It enables automatic transformation of primitive types, which aligns with the PR objective of fixing integer storage for ActorTypeEnum. This change enhances type safety and reduces the need for manual type casting in the controller.To ensure this change doesn't introduce any unexpected behavior, please verify that the
ActivityLogService.findActivityLogs
method correctly handles the transformed DTO. Run the following script to check the implementation:packages/core/src/shared/pipes/actor-type-transform.pipe.ts (3)
1-3
: LGTM: Imports are appropriate and well-organized.The imports are correctly chosen for the class functionality, and their order follows a good convention (external libraries first, then internal modules).
5-10
: LGTM: Well-structured class definition with appropriate documentation.The
ActorTypeTransformerPipe
class is well-defined:
- It correctly implements the
ValueTransformer
interface.- The class name is descriptive and follows naming conventions.
- The logger initialization is a good practice for debugging.
- The multi-line comment provides a clear explanation of the class purpose.
1-33
: Overall assessment: Well-implemented transformer with minor improvement suggestions.The
ActorTypeTransformerPipe
class effectively addresses the PR objective of managing the storage ofActorTypeEnum
in the database. It provides a clean and well-documented solution for transforming between application-level enums and database-level integers.Key strengths:
- Clear and descriptive class and method names
- Comprehensive documentation
- Proper implementation of the
ValueTransformer
interface- Effective use of logging for debugging purposes
Suggestions for improvement:
- Enhanced error handling in both
to
andfrom
methods to manage unexpected valuesThese minor enhancements will further improve the robustness of the implementation.
packages/core/src/activity-log/dto/get-activity-logs.dto.ts (2)
3-3
: LGTM: Import statement cleanupThe removal of the
ActorTypeEnum
import is consistent with the changes made to the DTO class. This cleanup helps maintain code cleanliness by removing unused imports.
Line range hint
1-52
: LGTM: Removal of redundant actorType property, but verify impactThe removal of the separate
actorType
property definition is consistent with its inclusion in thePickType
. This change simplifies the DTO and eliminates potential inconsistencies.Please verify that this change doesn't break existing functionality or API contracts. Run the following script to check for any remaining references to the removed
actorType
property in this file or related components:If any unexpected references are found, please update them accordingly.
packages/core/src/activity-log/activity-log.entity.ts (3)
9-9
: LGTM: Import statement for ActorTypeTransformerPipe added.The addition of this import aligns with the PR objective of addressing the integer storage for ActorTypeEnum. It suggests a new transformation mechanism for the
actorType
property, which is a good approach for handling enum storage in the database.
30-34
: LGTM: Simplified @ApiProperty decorator for 'action' property.The removal of the
type
attribute from the@ApiProperty
decorator simplifies the API documentation without affecting the functionality. This is a good practice for maintaining clean and concise code.
Line range hint
1-114
: Overall assessment: Changes effectively implement integer storage for ActorTypeEnum.The modifications in this file successfully address the PR objective of implementing integer storage for ActorTypeEnum in the database. The use of
ActorTypeTransformerPipe
is a clean and efficient solution for handling the conversion between enum values and their integer representations. The code changes are well-documented and maintain good practices in terms of API documentation and type safety.To ensure the changes are consistent across the codebase, please run the following verification script:
This script will help identify any inconsistencies or potential areas that might need similar treatment across the codebase.
packages/core/src/comment/comment.entity.ts (2)
16-16
: LGTM: Import statement added for ActorTypeTransformerPipeThe import of
ActorTypeTransformerPipe
is correctly added and will be used for theactorType
property transformation.
48-49
: 🛠️ Refactor suggestionReview the database storage changes for
actorType
The modifications to the
@MultiORMColumn
decorator introduce significant changes to howactorType
is stored in the database:
The column type is now set to 'int', and a transformer (ActorTypeTransformerPipe) is used. This change affects how the enum is stored and retrieved from the database.
The comment indicates that the value will be stored as 0 or 1 in the DB. While this provides clarity, it might be redundant if the
ActorTypeTransformerPipe
is well-documented.To ensure these changes don't introduce issues, please verify the following:
- Existing data migration: Confirm that a migration script exists to convert existing
actorType
values in the database to the new integer format.- Query impact: Check if any existing queries need to be updated due to this change.
You can use the following script to search for potential affected areas:
#!/bin/bash # Search for queries or operations involving actorType rg --type typescript 'actorType.*Comment'Consider the following improvements:
- If not already done, create a database migration script to handle the conversion of existing
actorType
values.- Update the comment to reference the
ActorTypeTransformerPipe
for more details on the transformation logic, rather than specifying the exact values.Example:
@MultiORMColumn({ type: 'int', nullable: true, transformer: new ActorTypeTransformerPipe() }) actorType?: ActorTypeEnum; // Transformed to int for DB storage. See ActorTypeTransformerPipe for details.packages/core/src/activity-log/activity-log.service.ts (2)
54-54
: Correct handling ofactorType
to include zero valuesThe condition
(actorType !== undefined && actorType !== null && { actorType })
ensures that anactorType
value of0
is not ignored. This is a good practice to accurately filter records whereactorType
can be zero.
35-35
: Verify method invocations due to parameter name changeThe parameter name in
findActivityLogs
has been changed fromfilter
tofilters
. Please ensure that all calls to this method are updated to reflect the new parameter name to prevent any runtime errors.You can run the following script to locate all usages of
findActivityLogs
:✅ Verification successful
Parameter Renaming Verified Successfully
All calls to
findActivityLogs
use positional arguments, and no updates are required for the parameter name change fromfilter
tofilters
. No runtime errors are expected.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Find all usages of `findActivityLogs` that may need to be updated. rg --type ts 'findActivityLogs\(' -A 2Length of output: 839
Script:
#!/bin/bash # Description: Find all usages of `findActivityLogs` with object destructuring to verify parameter names. rg --type ts 'findActivityLogs\s*\(\s*{' -A 3Length of output: 161
Script:
#!/bin/bash # Description: Find all usages of `findActivityLogs` with object destructuring to verify parameter names. rg --type ts 'findActivityLogs\s*\(\s*\{' -A 3Length of output: 390
☁️ Nx Cloud ReportCI is running/has finished running commands for commit 8060c55. As they complete they will appear below. Click to see the status, the terminal output, and the build insights. 📂 See all runs for this CI Pipeline Execution
✅ Successfully ran 5 targetsSent with 💌 from NxCloud. |
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 (4)
packages/core/src/shared/pipes/actor-type-transform.pipe.ts (1)
15-27
: LGTM with a minor suggestion: Methods are well-implemented and documented.The
to
andfrom
methods are correctly implemented, with clear documentation and consistent logic. They effectively handle the conversion betweenActorTypeEnum
and integer representations.For improved robustness, consider adding a default case or error handling for unexpected values:
to(value: ActorTypeEnum): number { - return value === ActorTypeEnum.User ? 1 : 0; // 1 for 'User', 0 for 'System' (default) + switch (value) { + case ActorTypeEnum.User: + return 1; + case ActorTypeEnum.System: + return 0; + default: + throw new Error(`Unexpected ActorTypeEnum value: ${value}`); + } } from(value: number): ActorTypeEnum { - return value === 1 ? ActorTypeEnum.User : ActorTypeEnum.System; + switch (value) { + case 1: + return ActorTypeEnum.User; + case 0: + return ActorTypeEnum.System; + default: + throw new Error(`Unexpected actor type value: ${value}`); + } }This change would make the code more explicit and handle potential errors if unexpected values are passed.
packages/core/src/activity-log/activity-log.service.ts (3)
Line range hint
21-36
: LGTM: Improved method signature and documentationThe change from
filter
tofilters
in the method signature is more accurate, reflecting the multiple filtering options available. The updated JSDoc provides clearer information about the method's purpose and usage.Consider adding
@throws
to the JSDoc to document any potential exceptions this method might throw.
50-55
: LGTM: Improved order handling logicThe new logic for handling result ordering is a good addition. It ensures that the method always uses valid ordering options and provides fallback values for invalid inputs.
Consider extracting the default values for
orderField
andorderDirection
into constants at the class or module level for better maintainability.
Line range hint
1-107
: Overall assessment: Significant improvements tofindActivityLogs
The changes to the
findActivityLogs
method in theActivityLogService
class represent a substantial improvement in functionality, robustness, and code quality. Key enhancements include:
- More flexible and precise filtering options
- Improved pagination and sorting logic
- Better handling of edge cases and invalid inputs
- Enhanced type safety with the use of
isNotNullOrUndefined
These changes address several past review comments and align well with best practices in TypeScript and NestJS development. The method is now more versatile and less prone to errors from invalid inputs.
Consider adding unit tests to cover the new logic, especially around pagination, sorting, and filtering, to ensure the method behaves correctly under various input scenarios.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- packages/core/src/activity-log/activity-log.service.ts (4 hunks)
- packages/core/src/shared/pipes/actor-type-transform.pipe.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (8)
packages/core/src/shared/pipes/actor-type-transform.pipe.ts (3)
1-2
: LGTM: Imports are correct and necessary.The imports for
ValueTransformer
from 'typeorm' andActorTypeEnum
from '@gauzy/contracts' are appropriate for the functionality of this class.
4-8
: LGTM: Well-documented and correctly implemented class.The
ActorTypeTransformerPipe
class is well-named, correctly implements theValueTransformer
interface, and is accompanied by clear and informative documentation explaining its purpose.
1-28
: Summary: Well-implemented solution addressing PR objectives.This new
ActorTypeTransformerPipe
class effectively addresses the PR objective of fixing integer storage forActorTypeEnum
in the database. It provides a clean, well-documented solution for converting between application-level enum values and database-level integer representations.The implementation is correct and follows good practices. With the minor suggestion for improved robustness, this class should effectively solve the issue of storing
ActorTypeEnum
values in the database as integers.packages/core/src/activity-log/activity-log.service.ts (5)
4-4
: LGTM: Improved type safety withisNotNullOrUndefined
importThe addition of
isNotNullOrUndefined
from '@gauzy/common' is a good practice. It enhances type safety and allows for more explicit null checks in the code.
Line range hint
38-48
: LGTM: Enhanced parameter handlingThe addition of
organizationId
andrelations
parameters, along with the default values forisActive
,isArchived
,orderBy
, andorder
, provides more flexibility and ensures consistent behavior when optional parameters are not provided.
59-63
: LGTM: Improved 'where' condition constructionThe use of concise object spread syntax for constructing the 'where' condition improves readability. The
isNotNullOrUndefined
check foractorType
addresses the potential issue with undefined values that was mentioned in a past review comment.
68-77
: LGTM: Improved pagination logicThe updated pagination logic addresses the past review comment about validating pagination parameters. The default
take
value and the validation ofskip
ensure that the method always uses valid pagination values, preventing incorrect offsets.
80-84
: LGTM: Improved query construction and executionThe changes ensure that sorting options are always applied, addressing a past review comment about consistent ordering. The use of
super.findAll
is a good practice as it utilizes the base class method for retrieving activity logs.
PR
Please note: we will close your PR without comment if you do not check the boxes above and provide ALL requested information.
Summary by CodeRabbit
New Features
ActorTypeTransformerPipe
for converting actor types between string and integer representations.Bug Fixes
actorType
to ensure proper filtering.Documentation
actorType
andaction
properties.Chores