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(utils): Add support for fetching remote JSON objects. #178

Merged
merged 11 commits into from
Feb 17, 2025

Conversation

junhaoliao
Copy link
Member

@junhaoliao junhaoliao commented Feb 7, 2025

Description

  1. Add utility to fetch an object from remote JSON.
    2. Add corresponding tests.

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

1. Ran npm run test and observed all tests succeeded, and there was no coverage violation.

Summary by CodeRabbit

  • New Features
    • Introduced a new asynchronous function for retrieving JSON data from remote URLs, enhancing data-fetching capabilities with improved error handling.
    • Updated export statement to include the new function alongside existing functionalities.

@junhaoliao junhaoliao requested a review from davemarco February 7, 2025 15:05
Copy link

coderabbitai bot commented Feb 7, 2025

Walkthrough

The pull request introduces an asynchronous function named getJsonObjectFrom that retrieves and parses a JSON object from a specified remote URL. This function returns a promise resolving to a parsed JSON object of type JsonValue and includes error handling that utilizes the convertAxiosError function for Axios errors. The export statement in the file is updated to include both getJsonObjectFrom and the existing getUint8ArrayFrom function.

Changes

File(s) Change Summary
src/utils/http.ts Added the getJsonObjectFrom function for fetching JSON from a remote URL with error handling via convertAxiosError. Updated export statement to include both getJsonObjectFrom and getUint8ArrayFrom.

Sequence Diagram(s)

sequenceDiagram
    participant C as Caller
    participant U as getJsonObjectFrom
    participant A as Axios

    C->>U: Call getJsonObjectFrom(remoteUrl)
    U->>A: Execute HTTP GET request
    A-->>U: Return response data
    alt Response is Object
        U->>C: Return parsed JSON object
    else Response is not an object
        U->>C: Return response as string
    end
    alt Request Error Occurs
        U->>C: Throw error after converting with convertAxiosError
    end
Loading

📜 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 cf71755 and ff6c68c.

📒 Files selected for processing (1)
  • src/utils/http.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/http.ts

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.

@junhaoliao
Copy link
Member Author

This PR depends on #177

@junhaoliao junhaoliao changed the title feat(http-utils): Add utility to fetch an object from remote JSON. feat(http): Add an HTTP utility to fetch an object from remote JSON. Feb 14, 2025
@junhaoliao junhaoliao marked this pull request as ready for review February 14, 2025 18:19
@junhaoliao
Copy link
Member Author

This PR depends on #177

As discussed offline with @davemarco , #177 is skipped for now.

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: 1

🧹 Nitpick comments (1)
src/utils/http.ts (1)

41-42: Consider adding type constraint for better type safety.

The generic type T is unconstrained, which could lead to runtime type mismatches if the JSON response doesn't match the expected type.

Consider adding a type constraint:

-const getJsonObjectFrom = async <T>(remoteUrl: string)
+const getJsonObjectFrom = async <T extends object>(remoteUrl: string)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 10b7cf5 and 22bfd34.

📒 Files selected for processing (1)
  • src/utils/http.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,ts,tsx}`: - Prefer `false ==

**/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

  • src/utils/http.ts
🔇 Additional comments (2)
src/utils/http.ts (2)

44-46: Consider adding caching control options.

Unlike getUint8ArrayFrom, this function doesn't specify any caching behaviour. Consider whether caching control should be consistent across both functions.

Would you like me to propose an implementation that includes caching control options?


83-86: LGTM!

The export statement is well-structured and follows TypeScript best practices.

Comment on lines 33 to 36
/**
* Retrieves an object that is stored as JSON in a remote location.
* If the response is not an object, the response is returned as a 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 inconsistency in JSDoc documentation.

The JSDoc comment states "If the response is not an object, the response is returned as a string", but the function signature Promise<T> doesn't reflect this behaviour. The function will actually return whatever type the JSON response maps to.

Apply this diff to fix the documentation:

 /**
  * Retrieves an object that is stored as JSON in a remote location.
- * If the response is not an object, the response is returned as a string.
+ * The response is parsed as JSON and cast to type T.
📝 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
/**
* Retrieves an object that is stored as JSON in a remote location.
* If the response is not an object, the response is returned as a string.
*
/**
* Retrieves an object that is stored as JSON in a remote location.
* The response is parsed as JSON and cast to type T.
*

@junhaoliao junhaoliao changed the title feat(http): Add an HTTP utility to fetch an object from remote JSON. feat(utils): Add an HTTP utility to fetch an object from remote JSON. Feb 14, 2025
* @return The parsed JSON object.
* @throws {Error} if the download fails.
*/
const getJsonObjectFrom = async <T>(remoteUrl: string)
Copy link
Contributor

Choose a reason for hiding this comment

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

Did you try and replace type T, with import {JsonValue} from "../typings/js"

Something like. Did this not work?

const getJsonObjectFrom = async (remoteUrl: string)
: Promise<JsonValue> => {
    try {
        const {data} = await axios.get<JsonValue>(remoteUrl, {
            responseType: "json",
        });

        return data;
    } catch (e) {
        throw (e instanceof AxiosError) ?
            convertAxiosError(e) :
            e;
    }
};

Copy link
Member Author

@junhaoliao junhaoliao Feb 14, 2025

Choose a reason for hiding this comment

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

ah, this is to supply type information for the data to be returned. e.g., user can now write

const profileNames = await getJsonObjectFrom<string[]>("/profile-names.json");

instead of

const profileNames = await getJsonObjectFrom("/profile-names.json") as unknown as string[];

Copy link
Contributor

@davemarco davemarco Feb 14, 2025

Choose a reason for hiding this comment

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

I think it would be better as JsonValue. It restricts the type more appropriately than T. Also you dont really know if string[], until validated. I think you can write

const profileNames = await getJsonObjectFrom("/profile-names.json") as string[];

Or add a type predicate isStringArray() if you really want

Copy link
Member Author

Choose a reason for hiding this comment

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

sure, that works

@junhaoliao junhaoliao requested a review from davemarco February 14, 2025 20:45
Comment on lines 36 to 37
* Retrieves an object that is stored as JSON in a remote location.
* If the response is not an object, the response is returned as a string.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
* Retrieves an object that is stored as JSON in a remote location.
* If the response is not an object, the response is returned as a string.
* Downloads JSON from remote url.

Copy link
Member Author

Choose a reason for hiding this comment

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

I do think it's worth mentioning a string would be returned for any non JSON response body, rather than anything thrown (especially now we don't have test cases to show the behavior). Shall we keep the last sentence?

Copy link
Contributor

Choose a reason for hiding this comment

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

Okay we can leave it.

Copy link
Member Author

Choose a reason for hiding this comment

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

How about:
Downloads and parses JSON from remote URL. If the HTTP response body is not JSON, the body is gracefully returned as a string.

Copy link
Contributor

Choose a reason for hiding this comment

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

Does it really parse? or does it just return a massive string?

Copy link
Contributor

Choose a reason for hiding this comment

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

Anyways I think your comment is fine, if it returns a js object

Copy link
Contributor

Choose a reason for hiding this comment

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

I look at your later PR, it looks like it parses. I think your comment is fine

* If the response is not an object, the response is returned as a string.
*
* @param remoteUrl
* @return The parsed JSON object.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
* @return The parsed JSON object.
* @return JSON response.

Copy link
Member Author

Choose a reason for hiding this comment

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

I think the original docstring is more clear

Copy link
Contributor

Choose a reason for hiding this comment

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

If it returns a string, it is not an object. While JSON is more like json value

Copy link
Member Author

@junhaoliao junhaoliao Feb 14, 2025

Choose a reason for hiding this comment

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

sure. how about:

@ return The parsed response.

Copy link
Contributor

Choose a reason for hiding this comment

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

@junhaoliao junhaoliao requested a review from davemarco February 14, 2025 21:01
Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

see latest comment

@junhaoliao junhaoliao requested a review from davemarco February 14, 2025 21:59
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: 0

🧹 Nitpick comments (1)
src/utils/http.ts (1)

43-56: Consider adding cache control headers for consistency.

The function could benefit from the same cache control headers as getUint8ArrayFrom to maintain consistent behaviour across HTTP utilities.

 const {data} = await axios.get<JsonValue>(remoteUrl, {
     responseType: "json",
+    headers: {
+        "Cache-Control": "no-cache",
+        "Pragma": "no-cache",
+        "Expires": "0",
+    },
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c29dd4 and cf71755.

📒 Files selected for processing (1)
  • src/utils/http.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,ts,tsx}`: - Prefer `false ==

**/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

  • src/utils/http.ts
🔇 Additional comments (3)
src/utils/http.ts (3)

3-3: LGTM! Import statement follows review discussion.

The import of JsonValue type aligns with the previous review discussion about using a more specific type instead of a generic T.


35-42: LGTM! Documentation reflects review discussion consensus.

The JSDoc documentation clearly describes the function's behaviour, including the handling of non-JSON responses.


85-88: LGTM! Export statement is well-organized.

The export statement properly includes both functions in alphabetical order.

Comment on lines 36 to 37
* Downloads and parses JSON from remote URL.
* If the HTTP response body is not JSON, the body is gracefully returned as a string.
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix wrapping no?

Copy link
Member Author

Choose a reason for hiding this comment

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

I revisited our coding guidelines and believe this description should instead be placed in the return value description. let me update the PR.

davemarco
davemarco previously approved these changes Feb 15, 2025
Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

I left a small nit, but can also just fix on next PR

@davemarco
Copy link
Contributor

title: feat(utils): Add support for fetching remote JSON objects.

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

approve see earlier title

@junhaoliao junhaoliao changed the title feat(utils): Add an HTTP utility to fetch an object from remote JSON. feat(utils): Add support for fetching remote JSON objects. Feb 17, 2025
@junhaoliao junhaoliao merged commit 97f4c39 into y-scope:main Feb 17, 2025
4 checks passed
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.

2 participants