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

Feature/implement the client ap is #20

Merged
merged 11 commits into from
Mar 15, 2025

Conversation

dhiashalabi
Copy link
Contributor

@dhiashalabi dhiashalabi commented Mar 15, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive API client that simplifies document management tasks such as fetching, updating, inserting, and deleting records.
    • Added a dedicated file download capability for streamlined access to files.
    • Expanded query options for document operations with enhanced filtering, grouping, and debugging support.
  • Refactor

    • Centralized API response and parameter definitions for improved modularity.
    • Updated error handling across various modules to enhance specificity and consistency.
    • Introduced a new utility function for handling HTTP requests, improving error management.
    • Updated module exports to make client functionalities more accessible.
  • Chores

    • Added configuration for automatic merging of pull requests to streamline the workflow.

- Removed the version comment from index.ts.
- Extracted FrappeResponse, TypedResponse, and ApiParams interfaces from index.ts to types.ts for better organization and modularity.
- Updated index.ts to import these types from the new file.
…meters

- Rearranged the order of properties in the GetDocListArgs interface for clarity.
- Moved the orFilters property to the end of the parameters in the FrappeDB class to improve readability.
- Ensured consistent handling of query parameters in the FrappeDB class.
- Added FrappeClient class to facilitate communication with the Frappe API, including methods for fetching, inserting, updating, and deleting documents.
- Introduced type definitions for request parameters in a new types.ts file, enhancing type safety and clarity.
- Each method includes error handling to manage API response errors effectively.
- Introduced FrappeFileDownload class to handle file download operations from a Frappe instance.
- Implemented downloadFile method to fetch files using Axios, with error handling for download failures.
- Added comprehensive documentation for the new class and its methods.
@dhiashalabi dhiashalabi self-assigned this Mar 15, 2025
Copy link

coderabbitai bot commented Mar 15, 2025

Walkthrough

This pull request reorganizes the codebase by centralizing API response and parameter type definitions. The FrappeResponse, TypedResponse, and ApiParams have been migrated from src/call/index.ts to a new file src/call/types.ts. A new FrappeClient class with multiple asynchronous methods for document operations has been introduced in the src/client directory along with new data retrieval interfaces. Changes in the database module adjust parameter ordering and extend list query options. Additionally, a new FrappeFileDownload class has been added for file download operations, and the main index now exports the client module.

Changes

File(s) Change Summary
src/call/index.ts
src/call/types.ts
Moved type definitions (FrappeResponse, TypedResponse, ApiParams) from index.ts to a centralized types.ts file for better modularity.
src/client/index.ts
src/client/types.ts
Added a new FrappeClient class with various asynchronous methods (getList, getCount, getDoc, etc.) for Frappe API interactions and introduced new interfaces (GetListArgs, GetCountArgs, GetDocArgs, GetValueArgs) for structured data retrieval.
src/db/index.ts
src/db/types.ts
Updated the getDocList method by reordering destructured parameters and assigning properties conditionally; extended the GetDocListArgs interface by adding new properties (groupBy, parent, debug).
src/file/index.ts Introduced a new FrappeFileDownload class with an asynchronous downloadFile method to handle file download operations while maintaining existing file upload functionality.
src/index.ts Removed the version comment and added an export statement to include functionalities from the client module in the main entry point.
.mergify.yml Added configuration for automatic merging of pull requests based on review status and labels.
src/auth/index.ts Updated error handling to replace generic Error with FrappeError in authentication methods.
src/frappe/types.ts Renamed the Error interface to FrappeError to enhance specificity in error handling.
src/utils/axios.ts Introduced RequestHandlerOptions interface and handleRequest function for improved request handling and error management.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant User
    participant FrappeClient
    participant Axios

    User->>FrappeClient: Call API method (e.g., getList)
    FrappeClient->>Axios: Send HTTP request
    Axios-->>FrappeClient: Return response or error
    FrappeClient-->>User: Deliver data or error details
Loading
sequenceDiagram
    participant User
    participant FrappeFileDownload
    participant Axios

    User->>FrappeFileDownload: Invoke downloadFile(fileURL)
    FrappeFileDownload->>Axios: GET request to /api/method/download_file?fileURL=...
    Axios-->>FrappeFileDownload: Return file data or error
    FrappeFileDownload-->>User: Send downloaded file data or error

Poem

I'm a bunny with a cheerful hop,
Code carrots lined up non-stop.
Types now in one cozy den,
Clients and files play roles again.
In a garden of code, I dance with glee—
Hopping to a smarter, neater spree!
🥕🐇 Happy coding from me!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 45d3c02 and 864daa2.

📒 Files selected for processing (1)
  • src/file/index.ts (3 hunks)

Note

🎁 Summarized by CodeRabbit Free

Your organization has reached its limit of developer seats under the Pro Plan. For new users, CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please add seats to your subscription by visiting https://app.coderabbit.ai/login.If you believe this is a mistake and have available seats, please assign one to the pull request author through the subscription management page using the link above.

🪧 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 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.

Copy link
Contributor

deepsource-io bot commented Mar 15, 2025

Here's the code health analysis summary for commits e3fd673..864daa2. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource JavaScript LogoJavaScript✅ Success
🎯 10 occurences resolved
View Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

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 (4)
src/file/index.ts (1)

234-248: Enhance error handling in the downloadFile method

While the implementation is functional, the error handling could be improved to match the level of detail provided in other methods like uploadFile.

async downloadFile(fileURL: string): Promise<void> {
-    const response = await this.axios.get(`/api/method/download_file`, {
-        params: {
-            file_url: fileURL,
-        },
-    })
-    return response.data
+    return this.axios
+        .get(`/api/method/download_file`, {
+            params: {
+                file_url: fileURL,
+            },
+        })
+        .then((response) => response.data)
+        .catch((error) => {
+            throw {
+                ...error.response?.data,
+                httpStatus: error.response?.status,
+                httpStatusText: error.response?.statusText,
+                message: error.response?.data?.message ?? 'There was an error while downloading the file.',
+                exception: error.response?.data?.exception ?? '',
+            } as Error
+        })
}
src/db/types.ts (1)

147-167: Synchronize pagination and filtering property names

You've introduced several new or repositioned parameters (groupBy, limit_start, limit, parent, debug, and orFilters) to expand interface flexibility. However, there's an inconsistency with other parts of the code (e.g. limit here vs. limit_page_length elsewhere). Consider aligning these naming conventions across all files to maintain consistency and reduce confusion.

src/client/types.ts (1)

1-59: Add clarity to pagination options

The newly added interfaces (GetListArgs, GetCountArgs, GetDocArgs, and GetValueArgs) increase the clarity and type safety of Frappe API calls. However, note the difference between limit in src/db/types.ts and limit_page_length here, which may lead to confusion for developers. Consider using consistent naming conventions across the codebase.

src/client/index.ts (1)

1-436: Refine request handling and naming consistency

  1. Verify that sending data via params in POST and PUT requests (e.g. setValue, insert, bulk_update) is the intended approach, since standard practice is to include the payload in the request body (data).
  2. The @ts-expect-error annotation for a private appURL indicates it's intentionally unused. If it's not needed, consider removing it or referencing it if required.
  3. Ensure pagination parameters match the definitions in src/db/types.ts (e.g. limit, limit_start vs. limit_page_length). Consistency will help avoid confusion in future maintenance.

Overall, the class layout is well-structured for multiple document operations.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e3fd673 and c1b0cd8.

📒 Files selected for processing (8)
  • src/call/index.ts (1 hunks)
  • src/call/types.ts (1 hunks)
  • src/client/index.ts (1 hunks)
  • src/client/types.ts (1 hunks)
  • src/db/index.ts (1 hunks)
  • src/db/types.ts (1 hunks)
  • src/file/index.ts (1 hunks)
  • src/index.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Mergify Merge Protections
🔇 Additional comments (9)
src/index.ts (1)

36-36: Export addition looks good!

The addition of export * from './client' appropriately exposes the new client module functionality from the main entry point of the SDK, matching the existing export pattern for other modules.

src/call/types.ts (3)

1-4: Well-defined base response type

The FrappeResponse interface is correctly defined with clear JSDoc comments explaining its purpose.


6-12: Well-implemented typed response interface

The TypedResponse<T> interface properly extends the base FrappeResponse interface, providing type safety for the message property through generics.


14-19: Good API parameters type definition

The ApiParams type is well-defined using the Record utility type to map string keys to various value types, with clear documentation explaining its purpose and type parameters.

src/db/index.ts (2)

176-177: Reordered destructuring looks good

The restructured parameter destructuring now includes the new groupBy parameter and reorders the properties in a logical way.


182-186: Consistent parameter mapping

The reordering of parameter assignments in the params object aligns with the destructured parameters order, and correctly handles the new group_by parameter.

src/file/index.ts (2)

219-231: Well-documented new class for file downloads

The FrappeFileDownload class is well-documented with clear JSDoc comments that explain its purpose and include usage examples.


232-232: Concise constructor implementation

The constructor is correctly implemented to accept and store an Axios instance for use in the download method.

src/call/index.ts (1)

28-28: Consolidating the type definitions

By importing ApiParams and TypedResponse from the newly created ./types module, you're enhancing modularity and maintainability. This is a solid improvement.

- Introduced a new .mergify.yml file to define rules for automatic merging and squashing of pull requests based on CI success and review approvals.
- Configured conditions to prevent merging with specific labels and set up commit message templates for squashed merges.
- Added a new `handleRequest` function to streamline Axios requests with customizable error handling and response transformation.
- Introduced `RequestHandlerOptions` interface to define options for the request handler, improving type safety and clarity.
- Integrated detailed error handling for Axios errors, providing structured error responses aligned with Frappe's error format.
- Replaced direct Axios error handling with a centralized `handleRequest` function in FrappeAuth, FrappeCall, FrappeClient, FrappeDB, and FrappeFileUpload classes.
- Updated error types from `Error` to `FrappeError` for consistency in error handling.
- Enhanced documentation to reflect changes in error throwing and request handling methods.

BREAKING CHANGE:
- Errors thrown from API requests now return `FrappeError` instead of `Error`.
  - This may affect existing try/catch implementations that expect standard `Error` properties like `name` or `stack`.
  - Ensure your error handling logic correctly handles `FrappeError` properties (`httpStatus`, `httpStatusText`, `exception`, etc.).
- The new `handleRequest` function replaces direct Axios calls in affected classes.
  - If you were relying on direct Axios responses or customizing Axios calls per method, you may need to update your logic.
- Changed string quotes in the downloadFile method of the FrappeFileDownload class from backticks to single quotes for consistency with the project's coding style.
… and FrappeDB classes

- Changed method signatures for get, post, put, delete, and other methods in FrappeCall, FrappeClient, and FrappeDB classes from async to synchronous, aligning with the new request handling approach.
- Updated method documentation to reflect the changes in return types and behavior.
…tion

- Replaced the async implementation of downloadFile in FrappeFileDownload class with a call to handleRequest for improved error handling and response transformation.
- Updated method parameters to align with the new request handling approach, enhancing consistency across file operations.
@dhiashalabi dhiashalabi merged commit 0d37ed7 into master Mar 15, 2025
9 checks passed
@dhiashalabi dhiashalabi deleted the feature/implement-the-client-APIs branch March 15, 2025 09:13
Copy link

🎉 This PR is included in version 2.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Successfully merging this pull request may close these issues.

None yet

1 participant