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

Fix/normalize export data #2530

Merged
merged 11 commits into from
Jul 2, 2024
Merged

Fix/normalize export data #2530

merged 11 commits into from
Jul 2, 2024

Conversation

jonathanfallon
Copy link
Member

@jonathanfallon jonathanfallon commented Jul 1, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new test cases for the get object helper function, covering various scenarios including retrieving values from nested objects and arrays.
  • Improvements

    • Enhanced file export functionality with better logging and error handling.
    • Updated environment variable handling to support multiple keys.
    • Improved file handling with new options for reading and writing files.
  • Bug Fixes

    • Fixed issues with type declarations and method calls to ensure proper functionality.
  • Documentation

    • Updated documentation to reflect changes in file handling and environment variable management.

@jonathanfallon jonathanfallon requested a review from nmrgt July 1, 2024 17:25
Copy link
Contributor

coderabbitai bot commented Jul 1, 2024

Walkthrough

Recent updates across various modules focused on enhancing file handling, environment variable management, and object utilities. Key changes include refining file operations, introducing more flexible environment variable defaults, and adding thorough test coverage for object manipulation utilities. These modifications improve code readability, maintainability, and robustness.

Changes

Files & Modules Summary
api/src/pdc/services/trip/actions/file/BuildFile.ts Refined file operations with better options for reading/writing, improved error logging.
api/src/lib/env/index.ts Enhanced env_or_default to handle arrays of keys for environment variable checking.
api/src/lib/file/index.ts Improved temporary directory handling; exported file-related types for better interfacing.
api/src/lib/object/get.unit.spec.ts Introduced new test cases covering various scenarios for the get object helper function.

Sequence Diagrams

File Handling Enhancement

sequenceDiagram
    participant Client
    participant BuildFile
    participant FileSystem

    Client ->> BuildFile: Request to create/update file
    BuildFile ->> FileSystem: Open file with write and append options
    FileSystem -->> BuildFile: File descriptor
    BuildFile ->> FileSystem: Write data in batches
    BuildFile -->> Client: Log file export status
    BuildFile ->> FileSystem: Close file
Loading

Enhanced Environment Variable Handling

sequenceDiagram
    participant Application
    participant EnvModule
    participant Environment

    Application ->> EnvModule: Request environment variable
    EnvModule ->> Environment: Check for multiple keys
    Environment -->> EnvModule: Return found value or fallback
    EnvModule -->> Application: Provide environment variable/fallback
Loading

🐇 In code we trust, in files we write,
With changes new, our code takes flight,
Batch by batch, logs shining bright,
Errors aside, everything's right. 😌


Tip

Early access features: enabled

We are currently testing the following features in early access:

  • OpenAI gpt-4o model for code reviews and chat: OpenAI claims that this model is better at understanding and generating code than the previous models. We seek your feedback over the next few weeks before making it generally available.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are currently opted into early access features by default.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
Contributor

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 119562c and 8f1c885.

Files selected for processing (7)
  • api/src/lib/file/index.ts (1 hunks)
  • api/src/lib/object/get.unit.spec.ts (1 hunks)
  • api/src/lib/object/index.ts (1 hunks)
  • api/src/lib/process/index.ts (1 hunks)
  • api/src/pdc/services/trip/actions/file/BuildFile.ts (7 hunks)
  • api/src/pdc/services/trip/helpers/normalizeExportDataHelper.ts (1 hunks)
  • api/src/shared/trip/sendExport.contract.ts (2 hunks)
Additional context used
Biome
api/src/shared/trip/sendExport.contract.ts

[error] 33-33: void is confusing outside a return type or a type parameter.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

api/src/pdc/services/trip/actions/file/BuildFile.ts

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

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


[error] 108-108: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Additional comments not posted (16)
api/src/shared/trip/sendExport.contract.ts (4)

1-1: LGTM!

The import statement is correct.


24-31: LGTM!

The changes improve type safety by using a constant array for ExportTypeList and defining ExportType based on it.


36-37: LGTM!

The changes ensure consistent use of double quotes in the handlerConfig object.


40-41: LGTM!

The changes ensure consistent use of double quotes in the signature constant.

api/src/lib/file/index.ts (2)

1-1: LGTM!

The import statement for join is correct and necessary for the getTmpDir function.


19-47: LGTM!

The type aliases OpenFileOptions and OpenFileDescriptor improve code readability. The open function is correctly implemented and includes helpful examples.

api/src/lib/object/index.ts (1)

3-30: LGTM!

The changes to the defaultValue parameter improve the get function by providing a default value of null. The function implementation correctly handles various scenarios.

api/src/lib/object/get.unit.spec.ts (1)

1-49: LGTM!

The test cases for the get function are comprehensive and cover various scenarios, ensuring the function works as expected.

api/src/lib/process/index.ts (1)

88-88: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to unhandledRejectionHandler match the new signature.

api/src/pdc/services/trip/actions/file/BuildFile.ts (6)

49-49: Ensure batch size is appropriate.

The batch size has been introduced as a private constant. Ensure that it is appropriate for the use case.


69-70: Consider combining error logs.

Consider combining the error message and stack trace into a single log entry for better readability.

-      logger.error(e.message);
-      logger.debug(e.stack);
+      logger.error(`${e.message}\n${e.stack}`);

33-37: LGTM!

The code changes are approved.


97-99: LGTM!

The code changes are approved.


22-22: Remove unnecessary constructor.

The constructor is unnecessary.

-  constructor() {}

Likely invalid or redundant comment.


33-37: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to buildCsvFromCursor match the new signature.

Verification successful

Verified function usage in the codebase.

The function call to buildCsvFromCursor in BuildExportAction.ts matches the new signature as defined in BuildFile.ts.

  • The function signature in BuildFile.ts:

    public async buildCsvFromCursor(
      cursor: PgCursorHandler<ExportTripInterface>,
      params: ParamsInterface,
      date: Date,
      isOpendata: boolean,
    ): Promise<string> {
  • The function call in BuildExportAction.ts:

    const filepath: string = await this.buildFile.buildCsvFromCursor(
      cursor,
      params,
      queryParams.date.end,
      isOpendata,
    );

The parameters match correctly.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `buildCsvFromCursor` match the new signature.

# Test: Search for the function usage. Expect: Only occurances of the new signature.
rg --type typescript $'buildCsvFromCursor'

Length of output: 76



Script:

#!/bin/bash
# Description: Verify all function calls to `buildCsvFromCursor` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg 'buildCsvFromCursor'

Length of output: 235



Script:

#!/bin/bash
# Description: Extract lines around the usage of `buildCsvFromCursor` in `BuildExportAction.ts` to verify it matches the new signature.

# Extract lines around the function call
rg -A 5 -B 5 'buildCsvFromCursor' api/src/pdc/services/trip/actions/BuildExportAction.ts

Length of output: 382



Script:

#!/bin/bash
# Description: Extract the function signature of `buildCsvFromCursor` from `BuildFile.ts` to verify the parameters.

# Extract the function signature
rg -A 5 -B 5 'buildCsvFromCursor' api/src/pdc/services/trip/actions/file/BuildFile.ts

Length of output: 346

api/src/pdc/services/trip/helpers/normalizeExportDataHelper.ts (1)

80-81: LGTM!

The code changes are approved.

Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8f1c885 and c94e38a.

Files selected for processing (3)
  • api/src/lib/object/get.unit.spec.ts (1 hunks)
  • api/src/lib/object/index.ts (1 hunks)
  • api/src/pdc/providers/middleware/Cast/CastToArrayMiddleware.ts (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • api/src/lib/object/get.unit.spec.ts
  • api/src/lib/object/index.ts

Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c94e38a and 73e1e47.

Files selected for processing (2)
  • api/src/pdc/services/trip/actions/file/BuildFile.ts (6 hunks)
  • api/src/shared/trip/sendExport.contract.ts (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • api/src/shared/trip/sendExport.contract.ts
Additional context used
Biome
api/src/pdc/services/trip/actions/file/BuildFile.ts

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

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


[error] 108-108: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Additional comments not posted (11)
api/src/pdc/services/trip/actions/file/BuildFile.ts (11)

1-3: Imports: Ensure consistency with usage.

The import modifications align with the changes in the method implementations. Ensure that all necessary imports are included and unused imports are removed.


22-22: Good practice: Use of constants.

The introduction of a batchSize constant improves code readability and maintainability.


33-37: Improvement: Default parameter value.

Setting a default value for params.type improves the robustness of the method.


39-40: Improvement: File opening options and logging.

Updating the file opening options to include writing and appending, along with adding a debug log, enhances functionality and traceability.


49-49: Improvement: Use of batch size constant.

Using the batchSize constant for reading from the cursor improves maintainability.


59-59: Ensure proper file closure.

The fd.close() method should be verified to ensure it is synchronous, as previously discussed.


66-67: Ensure proper file closure.

The fd.close() method should be verified to ensure it is synchronous, as previously discussed.


69-70: Improvement: Separate error logging.

Separating the error message and stack trace into different log levels improves debugging and log readability.


Line range hint 84-84: Improvement: Default values in cast method.

Providing default values for tz and filename improves the robustness of the method.


97-99: Improvement: Type adjustments.

Changing the type annotations to use primitive types (boolean and number) improves type safety.


108-108: Avoid assignment in expressions.

The assignment should not be in an expression. Refactor to improve readability.

-      while ((row = stringifier.read()) !== null) {
+      let row;
+      while ((row = stringifier.read()) !== null) {

Likely invalid or redundant comment.

Tools
Biome

[error] 108-108: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

api/src/pdc/services/trip/actions/file/BuildFile.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 73e1e47 and 4199e6d.

Files selected for processing (1)
  • api/src/pdc/services/trip/actions/file/BuildFile.ts (6 hunks)
Additional context used
Learnings (1)
api/src/pdc/services/trip/actions/file/BuildFile.ts (1)
Learnt from: jonathanfallon
PR: betagouv/preuve-covoiturage#2530
File: api/src/pdc/services/trip/actions/file/BuildFile.ts:66-67
Timestamp: 2024-07-02T07:48:51.054Z
Learning: The `fd.close()` method in the context of `BuildFile` class is not an async function and does not require the `await` keyword.
Biome
api/src/pdc/services/trip/actions/file/BuildFile.ts

[error] 106-106: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Additional comments not posted (8)
api/src/pdc/services/trip/actions/file/BuildFile.ts (8)

22-22: Good practice: Introduce constants for configuration.

Introducing the batchSize constant improves configurability and readability.


31-35: Update: Add default value for params.type.

Adding a default value for params.type in the cast method call ensures that the function handles missing or undefined params.type gracefully.


37-38: Update: Improve file opening options and logging.

The updated open method call with options for writing and appending, along with the debug log, enhances clarity and debugging capabilities.


47-47: Update: Use batchSize constant for cursor read.

Using the batchSize constant instead of a hardcoded value improves maintainability and configurability.


57-57: Clarification: fd.close() does not need await.

As per the user's previous feedback, fd.close() is not asynchronous and does not require the await keyword.


67-68: Refactor: Separate error logging.

Separating the error message and stack trace into different log levels improves readability and debugging.


31-35: Good practice: Handle default values for params.type.

Providing a default value for params.type ensures that the function operates correctly even with incomplete parameters.


95-97: Update: Improve type annotations.

Updating type annotations for boolean and number conversions improves type safety and readability.

Comment on lines +105 to 106
let row: string = "";
while ((row = stringifier.read()) !== null) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor: Avoid assignment in expressions.

The assignment should not be in an expression to improve readability and maintainability.

-      while ((row = stringifier.read()) !== null) {
+      let row;
+      while ((row = stringifier.read()) !== null) {

Committable suggestion was skipped due to low confidence.

Tools
Biome

[error] 106-106: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4199e6d and 505fb47.

Files selected for processing (3)
  • api/src/lib/env/index.ts (1 hunks)
  • api/src/lib/file/index.ts (1 hunks)
  • api/src/lib/object/get.unit.spec.ts (1 hunks)
Additional comments not posted (13)
api/src/lib/file/index.ts (3)

1-17: LGTM!

The changes to getTmpDir improve flexibility by checking multiple environment variables before falling back to a default value.


19-20: LGTM!

The introduction of OpenFileOptions and OpenFileDescriptor improves type safety and clarity for file operations.


22-46: LGTM!

The open function is well-implemented, with clear documentation and examples. The use of default options and the spread operator ensures flexibility.

api/src/lib/env/index.ts (1)

29-39: LGTM!

The envs_or_default function is a useful addition for checking multiple environment variables before falling back to a default value.

api/src/lib/object/get.unit.spec.ts (9)

5-8: LGTM!

The test case "should get value from object" is well-implemented and covers the expected behavior.


10-13: LGTM!

The test case "should get object from object" is well-implemented and covers the expected behavior.


15-18: LGTM!

The test case "should get value from indexed array" is well-implemented and covers the expected behavior.


20-23: LGTM!

The test case "should return default value if not found" is well-implemented and covers the expected behavior.


25-28: LGTM!

The test case "should return value from an array of objects" is well-implemented and covers the expected behavior.


30-34: LGTM!

The test case "should return value from an array of objects at root level" is well-implemented and covers the expected behavior.


36-39: LGTM!

The test case "should return default value if the obj is null or undefined" is well-implemented and covers the expected behavior.


41-45: LGTM!

The test case "should return null or undefined if the path ends and the value is null" is well-implemented and covers the expected behavior.


48-53: LGTM!

The test case "should return undefined as defaultValue if the defaultValue is not provided" is well-implemented and covers the expected behavior.

Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 505fb47 and a1ab4a9.

Files selected for processing (1)
  • api/src/lib/file/index.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • api/src/lib/file/index.ts

nmrgt
nmrgt previously approved these changes Jul 2, 2024
Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a1ab4a9 and bdd13da.

Files selected for processing (2)
  • api/src/lib/env/index.ts (1 hunks)
  • api/src/lib/file/index.ts (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • api/src/lib/env/index.ts
  • api/src/lib/file/index.ts

@jonathanfallon jonathanfallon merged commit 009d0d2 into main Jul 2, 2024
8 checks passed
@jonathanfallon jonathanfallon deleted the fix/normalize-export-data branch July 2, 2024 10:00
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.

None yet

2 participants