Skip to content

[sc-11931] handle POST request payload #87

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

Merged
merged 5 commits into from
May 26, 2025

Conversation

haoAddsearch
Copy link
Collaborator

@haoAddsearch haoAddsearch commented May 14, 2025

Summary by CodeRabbit

  • New Features

    • Added a method to specify the API request method (GET or POST).
    • Introduced a utility function to determine if an object is empty.
    • Updated documentation to inform users about POST API support limitations and configuration.
  • Refactor

    • Improved API request payload management by centralizing payload construction for consistency across API calls.

Copy link

coderabbitai bot commented May 26, 2025

Walkthrough

The changes add a setApiMethod method to specify HTTP method (GET or POST), refactor payload construction and response handling in API calls, and introduce a utility function to check for empty objects.

Changes

File(s) Change Summary
src/apifetch.ts Refactored API request payload construction, response handling, and added conditional POST/GET logic.
src/index.ts Added setApiMethod method to AddSearchClient for setting API method publicly.
src/settings.ts Introduced apiMethod property and setApiMethod in SettingsManager; defined ApiMethod type.
src/util.ts Added isEmptyObject utility function and updated exports.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AddSearchClient
    participant SettingsManager
    participant ApiFetch

    Client->>AddSearchClient: setApiMethod('POST')
    AddSearchClient->>SettingsManager: setApiMethod('POST')
    SettingsManager-->>AddSearchClient: (updates apiMethod)

    Client->>AddSearchClient: executeApiCall(settings)
    AddSearchClient->>ApiFetch: executeApiFetch(settings)
    ApiFetch->>ApiFetch: Build requestPayloadObject
    ApiFetch->>ApiFetch: Determine HTTP method (GET/POST) from settings
    ApiFetch->>ApiFetch: Make API request with payload
    ApiFetch->>ApiFetch: Handle response with handleApiResponse
    ApiFetch-->>AddSearchClient: Return API response
    AddSearchClient-->>Client: Return result
Loading

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.

npm warn config production Use --omit=dev instead.
npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-05-26T12_56_56_707Z-debug-0.log


📜 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 389465c and f8ba019.

📒 Files selected for processing (1)
  • src/apifetch.ts (11 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/apifetch.ts (2)
src/util.ts (1)
  • isEmptyObject (68-68)
src/api.ts (2)
  • RESPONSE_SERVER_ERROR (44-44)
  • apiInstance (39-39)
🔇 Additional comments (6)
src/apifetch.ts (6)

5-5: Good addition of utility import

The isEmptyObject utility import is well-placed and will be useful for validating object payloads.


125-125: Proper initialization of request payload object

Good practice to initialize the requestPayloadObject early for building POST request payloads.


184-209: Well-structured POST payload construction

The systematic construction of the request payload object is well-organized and covers all necessary search parameters. The parseInt usage for price fields correctly addresses the previous floating-point precision concerns.


227-243: Proper handling of custom field filters

The logic correctly processes custom field filters for both GET and POST requests, with appropriate use of isEmptyObject to conditionally include the field.


454-477: Good refactoring of response handling

The extraction of response handling into a dedicated function improves code organization and reusability.


489-505: Well-implemented conditional POST/GET logic

The conditional logic properly handles both POST and GET requests based on the apiMethod setting. The POST implementation correctly uses the constructed payload object while maintaining backward compatibility with GET requests.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

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

🧹 Nitpick comments (5)
src/util.ts (1)

60-60: Export list is starting to grow – consider grouping or re-exporting

Nothing wrong functionally, but the flat export list is becoming long. A barrel file or grouped exports (e.g. export * as util from './util') would improve discoverability as the module grows.

src/index.ts (1)

111-114: Five nearly identical throttle initialisations – DRY it up

this.throttledSearchFetch ??= throttle(...); is now repeated for search/aiAnswers/suggestions/autocomplete/recommendation.
Extracting a tiny helper like:

private initThrottle(bucket: 'search' | 'ai' | 'suggest' | 'autocomplete' | 'recommend') {
  const delay = this.settings.getSettings().throttleTimeMs;
  if (!this[`throttled${bucket}`]) {
    this[`throttled${bucket}`] = throttle(delay, executeApiFetch);
  }
}

would remove duplication and lower the risk of future inconsistencies.

src/settings.ts (1)

99-101: Default value is uppercase 'GET' – keep the enum case-safe

Backend APIs are often case-sensitive. If the server later expects lowercase ('get'|'post'), compilation won’t catch it. Consider enforcing/lowering case when persisting:

this.settings.apiMethod = 'GET'; // ➜ 'get'

and annotate the union type accordingly.

src/apifetch.ts (2)

230-244: Duplicate custom-field keys silently overwrite values

Building customFieldFiltersValues with customFieldFiltersValues[customFieldName] = customFieldValue means the last duplicate key wins.
If multiple values per field are allowed (e.g. color=red, color=blue), consider storing an array per field instead.


490-505: apiMethod === 'POST' excludes recommend

Calling setApiMethod('POST') and then recommend() still performs a GET request.
Clarify intent in docs or extend support to avoid mixed semantics.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7c3f54 and 30a0497.

📒 Files selected for processing (4)
  • src/apifetch.ts (11 hunks)
  • src/index.ts (8 hunks)
  • src/settings.ts (4 hunks)
  • src/util.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/apifetch.ts (2)
src/util.ts (1)
  • isEmptyObject (60-60)
src/api.ts (2)
  • RESPONSE_SERVER_ERROR (44-44)
  • apiInstance (39-39)
🔇 Additional comments (1)
src/apifetch.ts (1)

200-202:

❓ Verification inconclusive

Possible API field mismatch – sortByField

sortByField doesn’t appear elsewhere in the codebase or docs; the GET variant uses the parameter sort. Verify that the backend recognises sortByField – otherwise the POST request may silently ignore sorting.


🏁 Script executed:

#!/bin/bash
# 1. Find any occurrences of the `sortByField` key across the repository
rg -n "sortByField"

# 2. Inspect all `sort` occurrences (including GET params) around the snippet in src/apifetch.ts
rg -C3 "sort" -n src/apifetch.ts

Length of output: 1218


Validate backend sorting field for POST requests

The POST payload uses a sortByField key, whereas the GET endpoints use sort. Confirm that the backend API accepts sortByField; otherwise, sorting may be silently ignored.

• File: src/apifetch.ts
Lines: 200–202

      sortByField: settings?.paging.sortBy,
      sortOrder: settings?.paging.sortOrder

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

♻️ Duplicate comments (2)
src/apifetch.ts (2)

182-209: Comprehensive payload construction for search requests.

The POST payload construction covers all the necessary search parameters. However, there's still an issue with price parsing that was flagged in previous reviews.

The priceFromCents and priceToCents are still being parsed with parseFloat which can introduce floating-point inaccuracies since cents should be integers.

-      priceFromCents: settings?.priceFromCents ? parseFloat(settings?.priceFromCents) : undefined,
-      priceToCents: settings?.priceToCents ? parseFloat(settings?.priceToCents) : undefined,
+      priceFromCents: settings?.priceFromCents ? parseInt(settings?.priceFromCents, 10) : undefined,
+      priceToCents: settings?.priceToCents ? parseInt(settings?.priceToCents, 10) : undefined,

452-505: ⚠️ Potential issue

Critical issues remain unresolved in request handling.

The conditional POST/GET request handling is well-structured, but two critical issues from previous reviews persist:

  1. URI decoding issue: The POST flow blindly calls decodeURIComponent(keyword) without checking if the keyword was URI-encoded, which can cause URIError for special characters.

  2. Missing parameters in fuzzy retry: The recursive call omits customFilterObject and recommendOptions.

Apply these fixes:

    if (settings?.apiMethod === 'POST' && ['search', 'suggest', 'autocomplete'].includes(type)) {
      apiEndpoint = 'https://' + apiHostname + '/v1/' + apiPath + '/' + sitekey;
+     const term = type === 'search' ? decodeURIComponent(keyword) : keyword;
      requestPayloadObject = {
-       term: decodeURIComponent(keyword),
+       term: term,
        ...requestPayloadObject
      };
      apiInstance
        .post(apiEndpoint, requestPayloadObject)
        .then(handleApiResponse)
        .catch(handleApiError);
    } else {

And fix the fuzzy retry call:

-        executeApiFetch(apiHostname, sitekey, type, settings, cb, true);
+        executeApiFetch(
+          apiHostname,
+          sitekey,
+          type,
+          settings,
+          cb,
+          true,
+          customFilterObject,
+          recommendOptions
+        );
🧹 Nitpick comments (1)
README.md (1)

535-543: Fix heading level and approve documentation addition.

The new POST API documentation is helpful and clearly explains the new functionality. However, there's a heading level issue to fix.

Apply this diff to fix the heading level issue:

-#### Fetch AI answers
+### Fetch AI answers

The content effectively documents the new setApiMethod('POST') functionality and appropriately warns users about limited support.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

538-538: Heading levels should only increment by one level at a time
Expected: h3; Actual: h4

(MD001, heading-increment)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 30a0497 and 36a0dd0.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • package.json (1 hunks)
  • src/apifetch.ts (11 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/apifetch.ts (2)
src/util.ts (1)
  • isEmptyObject (60-60)
src/api.ts (2)
  • RESPONSE_SERVER_ERROR (44-44)
  • apiInstance (39-39)
🪛 markdownlint-cli2 (0.17.2)
README.md

538-538: Heading levels should only increment by one level at a time
Expected: h3; Actual: h4

(MD001, heading-increment)

🔇 Additional comments (6)
package.json (1)

3-3: Version bump looks good!

The minor version increment from "1.0.5" to "1.1.0" is appropriate for adding new POST API method functionality while maintaining backward compatibility.

src/apifetch.ts (5)

5-5: Good addition of utility import.

The import of isEmptyObject utility function supports the new payload construction logic effectively.


125-125: Good centralization of payload construction.

Initializing requestPayloadObject provides a clean foundation for building POST request payloads across different API call types.


228-242: Effective use of isEmptyObject utility.

The construction of custom field filters for POST payload correctly uses the isEmptyObject utility to avoid sending empty objects in the request.


247-255: Clean facet fields payload construction.

The facet fields are properly collected into an array and only included in the payload when not empty.


376-380: Consistent payload construction across API types.

The payload construction for suggest, autocomplete, and recommend requests follows the same pattern as search, providing good consistency across the codebase.

Also applies to: 413-417, 429-447

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

♻️ Duplicate comments (1)
src/apifetch.ts (1)

458-465: ⚠️ Potential issue

Recursive fuzzy retry still loses extra parameters
See previous review – issue remains.

customFilterObject and recommendOptions are not forwarded in the retry call, so the second request can differ from the first one.

-executeApiFetch(apiHostname, sitekey, type, settings, cb, true);
+executeApiFetch(
+  apiHostname,
+  sitekey,
+  type,
+  settings,
+  cb,
+  true,
+  customFilterObject,
+  recommendOptions
+);
🧹 Nitpick comments (2)
src/settings.ts (1)

69-73: Why keep apiMethod optional if you always initialise it?

apiMethod is declared as apiMethod?: ApiMethod; yet the constructor always sets a default ('GET').
Making the field non-optional (apiMethod: ApiMethod;) tightens the type system and removes the need for defensive undefined checks elsewhere.

-  apiMethod?: ApiMethod;
+  apiMethod: ApiMethod;
src/apifetch.ts (1)

188-189: Boolean → string conversion for fuzzy may surprise callers

JSON.stringify(true) results in the string "true", whereas the GET version sends fuzzy=true (string as well).
If the backend accepts raw booleans in JSON, consider passing the value unmodified:

-  fuzzy: fuzzy !== true && fuzzy !== false ? fuzzy : JSON.stringify(fuzzy),
+  fuzzy,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 36a0dd0 and 389465c.

📒 Files selected for processing (3)
  • src/apifetch.ts (11 hunks)
  • src/settings.ts (4 hunks)
  • src/util.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/apifetch.ts (2)
src/util.ts (1)
  • isEmptyObject (68-68)
src/api.ts (2)
  • RESPONSE_SERVER_ERROR (44-44)
  • apiInstance (39-39)
🔇 Additional comments (2)
src/util.ts (1)

56-66: isEmptyObject now guards all edge-cases – good job!

The added null / undefined guard, array check, and plain-object test resolve the runtime errors that were raised in the previous review.
Implementation is concise and safe.

src/settings.ts (1)

300-305: Runtime validation added – LGTM

The new guard prevents invalid strings at runtime and mirrors the compile-time ApiMethod union.
No further issues spotted.

Copy link

@haoAddsearch haoAddsearch merged commit 5ce2758 into master May 26, 2025
2 checks passed
@haoAddsearch haoAddsearch deleted the sc-11931/support-POST-api branch May 26, 2025 13:01
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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy