-
Notifications
You must be signed in to change notification settings - Fork 1
[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
Conversation
WalkthroughThe changes add a Changes
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
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
npm warn config production Use 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🧰 Additional context used🧬 Code Graph Analysis (1)src/apifetch.ts (2)
🔇 Additional comments (6)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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-exportingNothing 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-safeBackend 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 valuesBuilding
customFieldFiltersValues
withcustomFieldFiltersValues[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'
excludesrecommend
Calling
setApiMethod('POST')
and thenrecommend()
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
📒 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 parametersort
. Verify that the backend recognisessortByField
– 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.tsLength of output: 1218
Validate backend sorting field for POST requests
The POST payload uses a
sortByField
key, whereas the GET endpoints usesort
. Confirm that the backend API acceptssortByField
; otherwise, sorting may be silently ignored.• File: src/apifetch.ts
Lines: 200–202sortByField: settings?.paging.sortBy, sortOrder: settings?.paging.sortOrder
There was a problem hiding this 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
andpriceToCents
are still being parsed withparseFloat
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 issueCritical issues remain unresolved in request handling.
The conditional POST/GET request handling is well-structured, but two critical issues from previous reviews persist:
URI decoding issue: The POST flow blindly calls
decodeURIComponent(keyword)
without checking if the keyword was URI-encoded, which can causeURIError
for special characters.Missing parameters in fuzzy retry: The recursive call omits
customFilterObject
andrecommendOptions
.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 answersThe 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
📒 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
There was a problem hiding this 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 issueRecursive fuzzy retry still loses extra parameters
See previous review – issue remains.
customFilterObject
andrecommendOptions
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 keepapiMethod
optional if you always initialise it?
apiMethod
is declared asapiMethod?: 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 defensiveundefined
checks elsewhere.- apiMethod?: ApiMethod; + apiMethod: ApiMethod;src/apifetch.ts (1)
188-189
: Boolean → string conversion forfuzzy
may surprise callers
JSON.stringify(true)
results in the string"true"
, whereas the GET version sendsfuzzy=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
📒 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 – LGTMThe new guard prevents invalid strings at runtime and mirrors the compile-time
ApiMethod
union.
No further issues spotted.
|
Summary by CodeRabbit
New Features
Refactor