Skip to content

Conversation

codegen-sh[bot]
Copy link

@codegen-sh codegen-sh bot commented Jul 12, 2025

Summary

This PR adds comprehensive test coverage for the create and update methods in the MedusaService factory, addressing the bug where the update method was always returning arrays even when single objects were passed as input.

Changes Made

🧪 Test Coverage Added

  • Single object input/output tests: Validates that passing a single object returns a single object
  • Array input/output tests: Validates that passing an array returns an array
  • Service method call validation: Ensures underlying services are called with correct parameters
  • Comprehensive mocking: Added proper create and update method mocks for all container services

🐛 Bug Fix

  • Fixed update method: Changed const serviceData = Array.isArray(data) ? data : [data] to const serviceData = data
  • Preserves input type: The service now maintains input-output type consistency

Test Cases Added

Main Model Tests

  • createMainModelMocks with single object input → single object output
  • createMainModelMocks with array input → array output
  • updateMainModelMocks with single object input → single object output
  • updateMainModelMocks with array input → array output

Other Model Tests

  • createOtherModelMock1s with single object input → single object output
  • createOtherModelMock1s with array input → array output
  • updateOtherModelMock1s with single object input → single object output
  • updateOtherModelMock1s with array input → array output

Problem Solved

Before: The update method always wrapped input data in an array, causing inconsistent return types:

// Input: single object
const result = await service.updateTheme({ id: "1", name: "Updated" })
// Output: [{ id: "1", name: "Updated" }] ❌ (always array)

After: The update method preserves input type:

// Input: single object  
const result = await service.updateTheme({ id: "1", name: "Updated" })
// Output: { id: "1", name: "Updated" } ✅ (single object)

// Input: array
const result = await service.updateTheme([{ id: "1", name: "Updated" }])  
// Output: [{ id: "1", name: "Updated" }] ✅ (array)

Validation

These tests ensure that:

  1. Type consistency: Input type matches output type
  2. Service integration: Underlying services receive correct parameters
  3. Regression prevention: Future changes won't break this behavior
  4. Both methods covered: Both create and update methods are thoroughly tested

The tests would fail with the old buggy code and pass with the fixed implementation, providing robust validation of the fix.


Related to: Original issue where medusa-service generated update functions always return array of data even when only single object is passed

Requested by: @dwene


💻 View my workAbout Codegen

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of data input types in update operations, ensuring correct processing of both single objects and arrays.
  • Tests

    • Expanded test coverage for create and update operations to verify correct behavior with single and multiple input objects.

- Add tests for single object input/output consistency
- Add tests for array input/output consistency
- Add proper mocks for create/update service methods
- Fix update method to preserve input type (single object vs array)
- Tests validate the bug fix where update method was always returning arrays
Copy link

coderabbitai bot commented Jul 12, 2025

Walkthrough

The update modifies the internal handling of input data in the update method of the MedusaService factory, removing array normalization logic. Corresponding test mocks and cases are enhanced to cover both single object and array inputs for create and update methods, ensuring correct behavior and argument handling in various scenarios.

Changes

File(s) Change Summary
packages/core/utils/src/modules-sdk/medusa-service.ts Removed array normalization for input data in the update method, assigning input directly to the service call.
packages/core/utils/src/modules-sdk/tests/medusa-service.spec.ts Enhanced mocks and added tests for create and update methods with single and array inputs for various models.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MedusaService
    participant UnderlyingService

    Client->>MedusaService: update(data, context)
    MedusaService->>UnderlyingService: update(data, context)
    UnderlyingService-->>MedusaService: updatedData
    MedusaService->>Client: serialize(updatedData)
Loading

This diagram illustrates the revised control flow for the update method, where the input data is passed directly without normalization.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8c4228f and d6d773c.

📒 Files selected for processing (2)
  • packages/core/utils/src/modules-sdk/__tests__/medusa-service.spec.ts (4 hunks)
  • packages/core/utils/src/modules-sdk/medusa-service.ts (1 hunks)
🔇 Additional comments (5)
packages/core/utils/src/modules-sdk/medusa-service.ts (1)

246-246: Ignore flattening in update: underlying services handle shape normalization.

The update handler in medusa-service.ts correctly delegates to the container service’s own update method, which already returns either a single entity or an array based on your input (via shouldReturnArray in medusa-internal-service.ts). The generic wrapper then serializes that result, preserving the correct shape:

  • service.update(serviceData, …) returns a single model when called with an object, or an array when called with an array.
  • baseRepository_.serialize simply formats whatever shape it receives.

No additional array-vs-object post-processing is needed here. The original suggestion to add another flattening step is therefore unnecessary.

Likely an incorrect or invalid review comment.

packages/core/utils/src/modules-sdk/__tests__/medusa-service.spec.ts (4)

32-39: Excellent mock implementations for comprehensive testing.

The mock implementations correctly handle both single objects and arrays, returning the appropriate type based on input. This provides a solid foundation for testing the fixed update method behavior.

Also applies to: 47-52, 60-65


146-215: Comprehensive test coverage for main model create/update methods.

These test cases thoroughly verify:

  • Input/output type consistency for both single objects and arrays
  • Correct underlying service method invocation
  • Proper transaction context handling

The tests effectively validate that the fix preserves input types correctly.


280-349: Thorough test coverage for other model methods.

The test coverage extends to other models with the same comprehensive validation patterns, ensuring the fix works consistently across all generated service methods.


361-396: Consistent mock implementations across DML model services.

The DML model service mocks follow the same pattern as the main model mocks, ensuring comprehensive test coverage for custom configurations.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codegen-bot/add-medusa-service-tests

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this 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.

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.

0 participants