Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add extractRelatedResourceByName helper #59

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

thedeveloperr
Copy link

@thedeveloperr thedeveloperr commented Jan 10, 2025

Summary

This PR introduces the extractRelatedResourceByName function, which facilitates extracting relationship data from the included key of a JSON:API compliant API response using the relationship name.

Key Benefits:

  • Simplified Data Access: By using the relationship name, this function retrieves the relationship's data, reducing the need for manual data traversal and lookup logic by the developer, thus saving time.
  • Support for Multiple Relationships: Handles both single and multiple related resources.
  • Missing Data Handling: Returns undefined when relationships or included resources are missing.
  • Improved Code Readability: Encapsulates the logic for extracting related resources, leading to cleaner, less verbose code.

Changes

  • Add helper extractRelatedResourceByName and related tests

Videos/screenshots

Copy link

coderabbitai bot commented Jan 10, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/json-api/src/lib/response/extractRelatedResourceByName.spec.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/packages/json-api".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "packages/json-api/.eslintrc.json » ../../.eslintrc.json#overrides[0] » ./packages/eslint-config/src/index.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The pull request introduces a new utility function extractRelatedResourceByName for handling JSON:API resource relationships. This function is designed to extract related resources from an included array based on a specified relationship name. Accompanying the implementation, a comprehensive set of unit tests has been added to validate the function's behavior under various scenarios. A new JsonApiResource interface was also created to provide type definitions for JSON:API resource structures.

Changes

File Change Summary
packages/json-api/src/lib/types.ts Added JsonApiResource interface defining structure for JSON:API resources
packages/json-api/src/lib/response/extractRelatedResourceByName.ts Implemented extractRelatedResourceByName function to extract related resources from JSON:API responses
packages/json-api/src/lib/response/extractRelatedResourceByName.spec.ts Added comprehensive unit tests covering various scenarios for the new function

Sequence Diagram

sequenceDiagram
    participant Caller
    participant extractRelatedResourceByName
    participant Resource
    participant IncludedResources

    Caller->>extractRelatedResourceByName: Call with resource, included, relationshipName
    extractRelatedResourceByName->>Resource: Check relationships exist
    extractRelatedResourceByName->>IncludedResources: Check included resources defined
    extractRelatedResourceByName->>Resource: Get relationship data
    extractRelatedResourceByName->>IncludedResources: Match resources by type and id
    extractRelatedResourceByName-->>Caller: Return matched resource(s) or undefined
Loading

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@thedeveloperr thedeveloperr self-assigned this Jan 10, 2025
@thedeveloperr thedeveloperr force-pushed the feat-extractRelatedResourceByName branch from 3097fe1 to 5b254f4 Compare January 17, 2025 11:54
@thedeveloperr thedeveloperr marked this pull request as ready for review January 17, 2025 11:55
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (5)
packages/json-api/src/lib/types.ts (1)

80-80: Consider using a more specific type for attributes.

Instead of using Record<string, any>, consider creating a generic type parameter for attributes to improve type safety:

-  attributes?: Record<string, any>;
+  attributes?: Record<string, unknown>;
🧰 Tools
🪛 GitHub Actions: CI

[error] Code formatting check failed. File needs to be formatted according to project standards.

packages/json-api/src/lib/response/extractRelatedResourceByName.ts (2)

33-34: Improve type safety of filter operation.

The filter operation could be more explicit about removing undefined values:

-        .filter((element) => !!element);
+        .filter((element): element is JsonApiResource => element !== undefined);
🧰 Tools
🪛 GitHub Actions: CI

[error] Code formatting check failed. File needs to be formatted according to project standards.


16-18: Consider separating null checks.

For better error handling and debugging, consider separating the null checks:

-    if (!resource.relationships || !included) {
+    if (!resource.relationships) {
+      return undefined;
+    }
+    if (!included) {
       return undefined;
-    }
+    }
🧰 Tools
🪛 GitHub Actions: CI

[error] Code formatting check failed. File needs to be formatted according to project standards.

packages/json-api/src/lib/response/extractRelatedResourceByName.spec.ts (2)

52-76: Add test case for empty array relationship.

Consider adding a test case for when the relationship data is an empty array:

it("should return an empty array when relationship data is an empty array", () => {
  const apiResponse = {
    data: {
      type: "post",
      id: "1",
      relationships: {
        comments: {
          data: [],
        },
      },
    },
    included: [],
  };
  const result = extractRelatedResourceByName(
    apiResponse.data,
    apiResponse.included,
    "comments"
  );
  expect(result).toEqual([]);
});

93-105: Consider testing for mismatched type.

Add a test case for when the included resource has matching ID but different type:

it("should return undefined if included resource has matching id but different type", () => {
  const apiResponse = {
    data: {
      type: "book",
      id: "1",
      relationships: { author: { data: { type: "person", id: "1" } } },
    },
    included: [{ type: "organization", id: "1", attributes: { name: "Org" } }],
  };
  const result = extractRelatedResourceByName(
    apiResponse.data,
    apiResponse.included,
    "author"
  );
  expect(result).toBeUndefined();
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a590ad and 5b254f4.

📒 Files selected for processing (3)
  • packages/json-api/src/lib/response/extractRelatedResourceByName.spec.ts (1 hunks)
  • packages/json-api/src/lib/response/extractRelatedResourceByName.ts (1 hunks)
  • packages/json-api/src/lib/types.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
packages/json-api/src/lib/types.ts

[error] Code formatting check failed. File needs to be formatted according to project standards.

packages/json-api/src/lib/response/extractRelatedResourceByName.ts

[error] Code formatting check failed. File needs to be formatted according to project standards.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript-typescript)

Comment on lines +77 to +85
export interface JsonApiResource {
type: string;
id: string;
attributes?: Record<string, any>;
relationships?: Record<
string,
{ data: { type: string; id: string } | Array<{ type: string; id: string }> }
>;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix code formatting according to project standards.

The CI pipeline indicates formatting issues. Please run the project's formatter on this file.

🧰 Tools
🪛 GitHub Actions: CI

[error] Code formatting check failed. File needs to be formatted according to project standards.

Comment on lines +1 to +41
import { JsonApiResource } from "../types";
/**
* Extracts a related resource from the included array of a JSON:API response
* based on the relationship name.
*
* @param resource - The main resource containing the relationships.
* @param included - The included array from a JSON:API response.
* @param relationshipName - The name of the relationship to extract.
* @returns The related resource if found, otherwise undefined.
*/
export function extractRelatedResourceByName(
resource: JsonApiResource,
included: JsonApiResource[] | undefined,
relationshipName: string
): JsonApiResource | JsonApiResource[] | undefined {
if (!resource.relationships || !included) {
return undefined;
}

const relationship = resource.relationships[relationshipName];
if (!relationship?.data) {
return undefined;
}

if (Array.isArray(relationship.data)) {
return relationship.data
.map((data) =>
included?.find(
(includedResource) =>
includedResource.type === data.type && includedResource.id === data.id
)
)
.filter((element) => !!element);
}

const { type, id } = relationship.data;

return included.find(
(includedResource) => includedResource.type === type && includedResource.id === id
);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix code formatting according to project standards.

The CI pipeline indicates formatting issues. Please run the project's formatter on this file.

🧰 Tools
🪛 GitHub Actions: CI

[error] Code formatting check failed. File needs to be formatted according to project standards.

@@ -0,0 +1,106 @@
import { extractRelatedResourceByName } from "./jsonApiHelpers";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect import path.

The import statement appears to be incorrect:

- import { extractRelatedResourceByName } from "./jsonApiHelpers";
+ import { extractRelatedResourceByName } from "./extractRelatedResourceByName";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { extractRelatedResourceByName } from "./jsonApiHelpers";
import { extractRelatedResourceByName } from "./extractRelatedResourceByName";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant