Repository navigation
Improved graphql client - #1290
Conversation
|
Warning Rate limit exceeded@dangeredwolf has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 43 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThis update introduces a major refactor and enhancement of the Twitter GraphQL API integration. It centralizes and standardizes GraphQL query definitions and request handling, replacing scattered REST-like fetch calls with a unified Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant API
participant GraphQLRequest
participant TwitterAPI
Client->>API: Request tweet/thread/user data
API->>GraphQLRequest: Prepare query object & variables
GraphQLRequest->>TwitterAPI: Send GraphQL request (with queryId, variables, features)
TwitterAPI-->>GraphQLRequest: Return response data
GraphQLRequest-->>API: Validate and parse response
API-->>Client: Return processed data
Possibly related PRs
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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.
Actionable comments posted: 5
🔭 Outside diff range comments (2)
src/providers/twitter/fetch.ts (1)
164-164: 💡 Verification agent🧩 Analysis chain
Fix JSON parsing error in API response.
The pipeline shows a failure: "SyntaxError: Unexpected end of JSON input" at line 164. This suggests the API response is not returning valid JSON or the response is empty.
🏁 Script executed:
#!/bin/bash # Look for the structure of the GraphQL response handling # Check how responses are processed in the new GraphQL implementation rg "json\(\)" src/providers/twitter/graphql/Length of output: 46
I wasn’t able to locate any
.json()calls undersrc/providers/twitter/graphql/, which means the GraphQL handler likely doesn’t useresponse.json()there—or that path is incorrect. To confirm the root cause of the “Unexpected end of JSON input” at line 164 infetch.ts, can you help verify how that file handles empty or non-JSON responses? For example, does it guard onresponse.okor checkContent-Lengthbefore calling.json()?Please share the relevant lines around 160–180 in
src/providers/twitter/fetch.ts, or rerun:This will let us pinpoint whether we need a guard clause or a fallback for empty bodies.
🏁 Script executed:
#!/bin/bash sed -n '150,200p' src/providers/twitter/fetch.tsLength of output: 1870
Add a guard for empty or non-JSON Twitter API responses before parsing
To prevent the “Unexpected end of JSON input” error at line 164, make sure you check for a valid status and non-empty body before calling
.json().• src/providers/twitter/fetch.ts – line 164
Suggested diff:
- response = await apiRequest?.json(); + // 1) Ensure the request succeeded + if (!apiRequest.ok) { + console.error(`Twitter API returned status ${apiRequest.status}`); + return null; + } + + // 2) Guard against empty responses + const contentLength = apiRequest.headers.get('content-length'); + if (!contentLength || Number(contentLength) === 0) { + console.warn('Empty response from Twitter API'); + return null; + } + + // 3) Safely parse JSON + response = await apiRequest.json();🧰 Tools
🪛 GitHub Actions: Tests
[error] 164-164: Unknown error while fetching from API: SyntaxError: Unexpected end of JSON input
src/providers/twitter/conversation.ts (1)
383-423:⚠️ Potential issueNull-safety:
responsecan benull, causing the test failure
fetchSingleStatusexplicitly returnsnullwhen all endpoints fail, yet the code dereferencesresponse.databefore confirming it’s non-null.
This is the root cause of the pipeline failure (TypeError: Cannot read properties of null (reading 'data')).- let result: GraphQLTwitterStatus | null = null; + if (!response) { + writeDataPoint(c, language, null, '404'); + return { status: null, thread: null, author: null, code: 404 }; + } + + let result: GraphQLTwitterStatus | null = null;Add the same guard wherever
fetchSingleStatusis used.🧰 Tools
🪛 GitHub Actions: Tests
[error] 415-418: TypeError: Cannot read properties of null (reading 'data') during constructTwitterThread
♻️ Duplicate comments (1)
src/providers/twitter/conversation.ts (1)
300-305: Author-matching helper misses tweets returned viaTweetResultById
filterBucketStatusescurrently filters only onuser_results.
Tweets fetched throughTweetResultById/TweetResultsByIdsmay carryuser_result; this causes unrelated tweets to leak into the thread.See earlier type-comment for a suggested patch.
🧹 Nitpick comments (6)
src/providers/twitter/graphql/queries.ts (3)
156-157: Remove commented-out parameter in TweetResultByIdQuery.The commented
rest_idparameter suggests it should be set dynamically, but leaving commented code can cause confusion.- // rest_id: "", includeTweetVisibilityNudge: true
107-143: Consider documenting the higher rate limit of TweetResultsByIdsQuery.According to the PR objectives, this query offers a significantly higher rate limit compared to other queries, which is a key benefit worth documenting.
export const TweetResultsByIdsQuery: GraphQLQuery = { + // This query has a significantly higher rate limit than other Twitter GraphQL endpoints httpMethod: 'GET', queryId: 'vA1jTXbYyuy1QXGa0Xw8hA', queryName: 'TweetResultsByIdsQuery',
1-2: Consider adding a JSDoc comment describing the module's purpose.Adding documentation at the module level would help developers understand the centralized approach to GraphQL queries this file implements.
+/** + * Centralized GraphQL query definitions for Twitter API endpoints. + * These structured query objects are used with the graphqlRequest function + * to standardize API interactions across the application. + */ import { GraphQLQuery } from "./request"src/embed/activity.ts (1)
67-67: Keep or remove debug logging consistently.This commented out console.log statement looks like debugging code that was intentionally disabled. Consider whether to fully remove it rather than leaving it commented, as this would align with clean code practices.
- // console.log('quote!!', status.quote);src/providers/twitter/profile.ts (1)
3-3: Remove unused importThe
fetchUserimport is defined but never used in the code.-import { fetchUser } from './fetch';🧰 Tools
🪛 ESLint
[error] 3-3: 'fetchUser' is defined but never used.
(@typescript-eslint/no-unused-vars)
src/providers/twitter/conversation.ts (1)
307-369: Weight mutation without renormalisation may skew probabilityWhen Elongator is unavailable the weights are set to
1and0, but the earliernormalizedWeights
object was derived from the original totals.
Mutating it afterwards works but is brittle; a future change that adds more endpoints will silently break the invariant (sum = 1).Consider recalculating or wrapping the weighting logic:
const pickEndpoint = () => { const weights = experimentCheck(/* … */) ? { TweetResultsByRestId: 50, TweetResultsByIds: 500 } : { TweetResultsByRestId: 1 }; const total = Object.values(weights).reduce((a, b) => a + b, 0); const r = Math.random() * total; let acc = 0; return Object.entries(weights).find(([_, w]) => (acc += w) >= r)![0]; };🧰 Tools
🪛 GitHub Actions: Tests
[error] 346-347: TypeError: Cannot read properties of null (reading 'data') during fetchSingleStatus
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
src/embed/activity.ts(1 hunks)src/helpers/translate.ts(1 hunks)src/providers/twitter/conversation.ts(14 hunks)src/providers/twitter/fetch.ts(2 hunks)src/providers/twitter/graphql/queries.ts(1 hunks)src/providers/twitter/graphql/request.ts(1 hunks)src/providers/twitter/processor.ts(1 hunks)src/providers/twitter/profile.ts(2 hunks)src/types/vendor/twitter.d.ts(2 hunks)test/helpers/env-wrapper.ts(1 hunks)test/mocks/TweetResultsByIds/1841206275088290279.json(1 hunks)test/mocks/TweetResultsByIds/1848831595014459513.json(1 hunks)test/mocks/TweetResultsByIds/1899954694652309701.json(1 hunks)test/mocks/TweetResultsByIds/1902059299591090335.json(1 hunks)test/mocks/TweetResultsByIds/20.json(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/providers/twitter/processor.ts (1)
src/providers/twitter/profile.ts (1)
convertToApiUser(9-68)
src/providers/twitter/conversation.ts (4)
src/providers/twitter/graphql/request.ts (1)
graphqlRequest(25-38)src/providers/twitter/graphql/queries.ts (4)
TweetDetailQuery(50-105)TweetResultByRestIdQuery(3-48)TweetResultsByIdsQuery(107-143)TweetResultByIdQuery(145-181)src/helpers/graphql.ts (1)
isGraphQLTwitterStatus(15-23)src/experiments.ts (1)
experimentCheck(61-66)
src/providers/twitter/graphql/queries.ts (1)
src/providers/twitter/graphql/request.ts (1)
GraphQLQuery(7-16)
🪛 GitHub Actions: Tests
src/embed/activity.ts
[error] 262-262: Error in handleActivity due to missing ExecutionContext and invalid API response
src/providers/twitter/fetch.ts
[error] 164-164: Unknown error while fetching from API: SyntaxError: Unexpected end of JSON input
test/helpers/env-wrapper.ts
[error] 67-67: Error: Invalid request while fetching from API
src/providers/twitter/conversation.ts
[error] 346-347: TypeError: Cannot read properties of null (reading 'data') during fetchSingleStatus
[error] 415-418: TypeError: Cannot read properties of null (reading 'data') during constructTwitterThread
🪛 ESLint
src/providers/twitter/profile.ts
[error] 3-3: 'fetchUser' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 Biome (1.9.4)
test/helpers/env-wrapper.ts
[error] 56-56: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
src/providers/twitter/conversation.ts
[error] 444-444: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🔇 Additional comments (14)
test/mocks/TweetResultsByIds/1899954694652309701.json (1)
1-264: The mock data is well-structured and follows the expected Twitter GraphQL API format.This mock file provides comprehensive test data with all necessary components of a Twitter API response, including user information, poll card data, and engagement metrics.
test/mocks/TweetResultsByIds/1841206275088290279.json (1)
1-306: Properly structured mock for a tweet with video content.This mock correctly includes video variants with different resolutions and bitrates, which is essential for testing the application's handling of video tweet content.
test/mocks/TweetResultsByIds/1848831595014459513.json (1)
1-670: Well-formed mock for a multi-image tweet response.The mock data contains all necessary fields and proper structure for a tweet with multiple images, including different size variations for each image.
src/providers/twitter/graphql/queries.ts (1)
1-199: Well-structured GraphQL query definitions with comprehensive feature flags.The query definitions follow a consistent pattern and include detailed feature configurations that match Twitter's API requirements.
src/embed/activity.ts (1)
261-263:Details
❌ Incorrect review comment
Fix the pipeline test failure.
The pipeline shows a failure on line 262: "Error in handleActivity due to missing ExecutionContext and invalid API response". This may be related to the new GraphQL implementation's response structure.
🏁 Script executed:
#!/bin/bash # Check if handleActivity is correctly handling the updated response format # from the new GraphQL implementation # Look for calls to constructTwitterThread rg -A 5 "constructTwitterThread" src/Length of output: 4010
🏁 Script executed:
#!/bin/bash set -e echo "=== Reading constructTwitterThread signature & initial implementation ===" sed -n '1,100p' src/providers/twitter/conversation.ts echo echo "=== Searching for GraphQL usage within constructTwitterThread ===" rg -C3 "graphql" src/providers/twitter/conversation.ts || true echo echo "=== Locating handleActivity in embed/activity.ts ===" rg -C10 "handleActivity" src/embed/activity.ts || trueLength of output: 7077
🏁 Script executed:
#!/bin/bash set -e echo "=== Extracting handleActivity block (lines 240–300) from src/embed/activity.ts ===" sed -n '240,300p' src/embed/activity.tsLength of output: 1766
🏁 Script executed:
#!/bin/bash set -e echo "=== Searching for SocialThread type definition ===" rg -n "type SocialThread" -n src/types/types.ts || rg -n "interface SocialThread" -n src/types/types.tsLength of output: 342
🏁 Script executed:
#!/bin/bash set -e echo "=== Listing all files under src/types ===" find src/types -type f || true echo echo "=== Searching for SocialThread in repository ===" rg -n "SocialThread" -n .Length of output: 1118
🏁 Script executed:
#!/bin/bash set -e echo "=== Searching for executionContext usage in twitter/conversation.ts ===" rg -n "executionContext" -n src/providers/twitter/conversation.ts || true echo echo "=== Searching for waitUntil usage in twitter/conversation.ts ===" rg -n "waitUntil" -n src/providers/twitter/conversation.ts || trueLength of output: 447
🏁 Script executed:
#!/bin/bash set -e echo "=== Displaying the webpack request implementation ===" sed -n '1,200p' src/providers/twitter/graphql/request.ts || trueLength of output: 1521
Ignore missing ExecutionContext — handleActivity correctly uses Hono Context
After verifying
constructTwitterThread,graphqlRequest, andhandleActivity, there are no references to anExecutionContextorwaitUntilin these modules. The GraphQL response is validated ingraphqlRequestvia itsvalidatorcallbacks, andhandleActivityconsumes the resultingSocialThreadas expected. The reported error on line 262 is not caused by a missingExecutionContextin this code path, so no changes are required here.Likely an incorrect or invalid review comment.
🧰 Tools
🪛 GitHub Actions: Tests
[error] 262-262: Error in handleActivity due to missing ExecutionContext and invalid API response
src/helpers/translate.ts (1)
64-64: Good addition of fallback for tweet ID extraction.Adding
tweet.legacy?.conversation_id_stras another fallback improves robustness when handling Twitter API responses with varying tweet ID fields. This aligns with similar fallback logic implemented elsewhere in the codebase.src/providers/twitter/fetch.ts (2)
2-5: Improved import path organization.Updating import paths to use higher-level directory imports rather than relative imports improves code organization and maintainability.
196-197: Corrected type assertion for NSFW detection.Updating the type assertion from
TweetResultsByRestIdResulttoTweetResultsByRestIdResponseensures proper type checking with the updated type definitions.src/providers/twitter/processor.ts (2)
54-54: Enhanced user extraction with fallback pathThe implementation now handles multiple Twitter API response structures by adding a fallback path from
user_resultstouser_result. This makes the code more robust against API variations.
58-58: Improved tweet ID extraction with multiple fallbacksThis change adds progressive fallbacks for tweet ID extraction: first trying
rest_id, thenlegacy.id_str, and finallylegacy?.conversation_id_str. This makes the code more resilient against inconsistent API responses.The fallback to
conversation_id_stris particularly useful as mentioned in the issue reference comment (line 57), protecting against undefinedrest_idcases.src/providers/twitter/profile.ts (2)
6-7: Added GraphQL infrastructure importsThese new imports support the refactored GraphQL request implementation, providing better abstraction for API queries.
92-104: Refactored user fetching to use GraphQL infrastructureThe implementation now leverages the new GraphQL infrastructure with several benefits:
- Uses standardized query definitions from a central location
- Adds explicit validation of response structure
- Improves type safety with appropriate casting
This change aligns with the PR objective of abstracting GraphQL complexities.
The validator function properly checks both for the correct
__typenameand the existence of required legacy data, ensuring robust error handling.test/mocks/TweetResultsByIds/1902059299591090335.json (1)
1-399: Well-structured mock for TweetResultsByIds endpointThis comprehensive mock provides test coverage for the new GraphQL API response format, including:
- Complete user profile information
- Video media with multiple bitrate variants
- Nested quoted tweet data
- View counts and engagement metrics
The mock follows the structure expected by the refactored GraphQL client and supports testing the new tweet fetching approach.
test/mocks/TweetResultsByIds/20.json (1)
1-126: Mock for historic first tweetThis mock provides a well-structured test case for Jack Dorsey's iconic first tweet, complete with:
- User verification and profile details
- Engagement metrics (likes, retweets, etc.)
- Business affiliation labels
The mock will enable testing with a widely recognized, historically significant tweet ID.
| case 'TweetResultsByIds': | ||
| const tweetIds = variables.tweetIds; | ||
| // load mock based on tweet ids | ||
| try { | ||
| const mock = await import(`../mocks/TweetResultsByIds/${tweetIds}.json`); | ||
| console.log('Mock data:', mock); | ||
| return new Response(JSON.stringify(mock)); | ||
| } catch (error) { | ||
| console.error('Error loading mock:', error); | ||
| } | ||
| return new Response(JSON.stringify({ data: {} })); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Fix switch statement variable declaration scope.
Your new case implementation for TweetResultsByIds looks good, but it has a static analysis warning about variable declaration. The variable tweetIds could be accessed by other switch cases, which is considered unsafe.
Fix this by wrapping the case content in a block to restrict variable scope:
case 'TweetResultsByIds':
+ {
const tweetIds = variables.tweetIds;
// load mock based on tweet ids
try {
const mock = await import(`../mocks/TweetResultsByIds/${tweetIds}.json`);
console.log('Mock data:', mock);
return new Response(JSON.stringify(mock));
} catch (error) {
console.error('Error loading mock:', error);
}
return new Response(JSON.stringify({ data: {} }));
+ }📝 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.
| case 'TweetResultsByIds': | |
| const tweetIds = variables.tweetIds; | |
| // load mock based on tweet ids | |
| try { | |
| const mock = await import(`../mocks/TweetResultsByIds/${tweetIds}.json`); | |
| console.log('Mock data:', mock); | |
| return new Response(JSON.stringify(mock)); | |
| } catch (error) { | |
| console.error('Error loading mock:', error); | |
| } | |
| return new Response(JSON.stringify({ data: {} })); | |
| case 'TweetResultsByIds': { | |
| const tweetIds = variables.tweetIds; | |
| // load mock based on tweet ids | |
| try { | |
| const mock = await import(`../mocks/TweetResultsByIds/${tweetIds}.json`); | |
| console.log('Mock data:', mock); | |
| return new Response(JSON.stringify(mock)); | |
| } catch (error) { | |
| console.error('Error loading mock:', error); | |
| } | |
| return new Response(JSON.stringify({ data: {} })); | |
| } |
🧰 Tools
🪛 Biome (1.9.4)
[error] 56-56: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
| } | ||
| return new Response(JSON.stringify({ data: {} })); | ||
| default: | ||
| throw new Error('Invalid request'); |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Fix the pipeline test failure with "Invalid request".
The test pipeline shows an error on line 67: "Error: Invalid request while fetching from API". This might be caused by improper mock data handling or missing mock files.
🏁 Script executed:
#!/bin/bash
# Check what mock files are available for TweetResultsByIds
# List all mock files for TweetResultsByIds
find test/mocks/TweetResultsByIds -type f -name "*.json" | sortLength of output: 318
Ensure mock JSON exists for every Tweet ID used in tests
The 'Invalid request' error in test/helpers/env-wrapper.ts (line 67) indicates that the helper couldn’t find a mock file for the requested Tweet ID. Currently, your mock directory contains only these files:
- test/mocks/TweetResultsByIds/20.json
- test/mocks/TweetResultsByIds/1841206275088290279.json
- test/mocks/TweetResultsByIds/1848831595014459513.json
- test/mocks/TweetResultsByIds/1899954694652309701.json
- test/mocks/TweetResultsByIds/1902059299591090335.json
Action items:
- Verify which Tweet ID your failing test is requesting.
- If it’s not one of the IDs above, add the corresponding
*.jsontotest/mocks/TweetResultsByIds/. - Alternatively, update the test to use an existing mock (e.g.,
20.json).
🧰 Tools
🪛 GitHub Actions: Tests
[error] 67-67: Error: Invalid request while fetching from API
| user_results?: { | ||
| result: GraphQLUser; | ||
| }; | ||
| user_result?: { | ||
| result: GraphQLUser; | ||
| }; | ||
| }; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Filter helpers now ignore the new user_result field
You added core.user_result as a nullable alternative to core.user_results, but downstream code (e.g. filterBucketStatuses in conversation.ts) still only checks tweet.core?.user_results.
Please extend those helpers (or create a utility) so both shapes are honoured; otherwise threads composed from TweetResultsByIds may fail to match the author filter.
Example fix for filterBucketStatuses:
-return tweets.filter(
- tweet =>
- tweet.core?.user_results?.result?.rest_id ===
- original.core?.user_results?.result?.rest_id
-);
+return tweets.filter(tweet => {
+ const restId =
+ tweet.core?.user_results?.result?.rest_id ??
+ tweet.core?.user_result?.result?.rest_id;
+ const originalRestId =
+ original.core?.user_results?.result?.rest_id ??
+ original.core?.user_result?.result?.rest_id;
+ return restId === originalRestId;
+});Committable suggestion skipped: line range outside the PR's diff.
There was a problem hiding this comment.
We only expect user_result to be present if we are using the TweetResultsByIds endpoint, but this code relates to TweetDetail endpoint, so it shouldn't affect it in any real scenario. But I'm not sure if there are other improvements I can make to the typing to make this clearer--the types otherwise align other than these slight differences.
There was a problem hiding this comment.
🧩 Analysis chain
After checking the code, I'll provide a suggestion on how to improve the typing for clarity.
🏁 Script executed:
#!/bin/bash
# Find the filterBucketStatuses function mentioned in the review
rg "filterBucketStatuses" -A 10 -B 5
# Check how the tweet.core.user_results and tweet.core.user_result fields are accessed
rg "core\.(user_results|user_result)" -A 3 -B 3
# Also check the processor.ts file mentioned in the ai_summary
cat src/providers/twitter/processor.ts | grep -A 10 -B 5 "user_result\|user_results"
Length of output: 6347
🏁 Script executed:
#!/bin/bash
# Let's check where filterBucketStatuses is used more broadly and how tweets from different endpoints are processed
rg "filterBucketStatuses" --context=15
# Also check if there are any other places that need to access user information from tweets
rg "(user_results|user_result).*rest_id" -A 2 -B 2
# Check if there are any utility functions to extract users from tweets already
rg "function.*extract.*user" -i
Length of output: 9579
@dangeredwolf Looking at the code, I can see you're already using the correct pattern in processor.ts with:
const graphQLUser = (status.core.user_results?.result ?? status.core.user_result?.result) as GraphQLUser;You're right that different endpoints return different shapes. For improved typing, you could:
- Create a utility function to extract the user ID that handles both shapes:
// Add to a utils file
export function getUserRestId(tweet: GraphQLTwitterStatus): string | undefined {
return tweet.core?.user_results?.result?.rest_id ??
tweet.core?.user_result?.result?.rest_id;
}- Add JSDoc comments to the type to document which fields come from which endpoints:
type GraphQLTwitterStatus = {
// Other properties...
core: {
/**
* Contains user data for tweets returned by TweetDetail and TweetResultByRestId endpoints
*/
user_results?: {
result: GraphQLUser;
};
/**
* Contains user data for tweets returned by TweetResultsByIds endpoint
*/
user_result?: {
result: GraphQLUser;
};
};
// Other properties...
};This way, the type itself documents the endpoint-specific behavior while still allowing your code to handle both cases.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
test/helpers/env-wrapper.ts (1)
55-65:⚠️ Potential issueFix variable scope in switch case and update to handle array rest_ids.
The new
TweetResultsByIdscase has two issues:
- The
tweetIdsvariable declaration has a static analysis warning about scope - it should be wrapped in a block- It uses
variables.tweetIdsbut the GraphQL query actually passesvariables.rest_idsas an arrayApply these fixes to address variable scope and handle the correct parameter:
case 'TweetResultsByIds': + { - const tweetIds = variables.tweetIds; + const ids = Array.isArray(variables.rest_ids) + ? variables.rest_ids + : [variables.rest_ids]; + const filename = ids.join(','); // load mock based on tweet ids try { - const mock = await import(`../mocks/TweetResultsByIds/${tweetIds}.json`); + const mock = await import(`../mocks/TweetResultsByIds/${filename}.json`); console.log('Mock data:', mock); return new Response(JSON.stringify(mock)); } catch (error) { console.error('Error loading mock:', error); } return new Response(JSON.stringify({ data: {} })); + }These changes address previous pipeline failures and align with how the GraphQL query parameters are actually structured.
🧰 Tools
🪛 Biome (1.9.4)
[error] 56-56: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🧹 Nitpick comments (2)
src/providers/twitter/conversation.ts (2)
444-452: Improve optional chaining usage.The code could benefit from using optional chaining to improve readability and reduce the chance of null reference errors.
Simplify the code with optional chaining:
-if ((response as TweetResultsByRestIdResponse).data.tweetResult?.result) { - result = (response as TweetResultsByRestIdResponse).data.tweetResult?.result as GraphQLTwitterStatus; +if ((response as TweetResultsByRestIdResponse).data?.tweetResult?.result) { + result = (response as TweetResultsByRestIdResponse).data?.tweetResult?.result as GraphQLTwitterStatus; -} else if ((response as TweetResultsByIdsResponse).data.tweet_results?.[0]?.result) { - result = (response as TweetResultsByIdsResponse).data.tweet_results?.[0]?.result as GraphQLTwitterStatus; +} else if ((response as TweetResultsByIdsResponse).data?.tweet_results?.[0]?.result) { + result = (response as TweetResultsByIdsResponse).data?.tweet_results?.[0]?.result as GraphQLTwitterStatus; -} else if ((response as TweetResultByIdResponse).data.tweet_result?.result) { - result = (response as TweetResultByIdResponse).data.tweet_result?.result as GraphQLTwitterStatus; +} else if ((response as TweetResultByIdResponse).data?.tweet_result?.result) { + result = (response as TweetResultByIdResponse).data?.tweet_result?.result as GraphQLTwitterStatus; }This change aligns with the static analysis hint and prevents potential null reference errors.
🧰 Tools
🪛 Biome (1.9.4)
[error] 444-444: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
383-383: Improve type declaration by adding explicit null handling.The type declaration for
responseincludes multiple response types but doesn't explicitly acknowledge that it could be null.For better type safety, explicitly add null to the type union:
-let response: TweetDetailResponse | TweetResultsByRestIdResponse | TweetResultsByIdsResponse | TweetResultByIdResponse | null = null; +let response: TweetDetailResponse | TweetResultsByRestIdResponse | TweetResultsByIdsResponse | TweetResultByIdResponse | null = null;While the code already initializes this as null, explicitly including it in the type helps with the readability and reminds developers to handle the null case.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/providers/twitter/conversation.ts(14 hunks)test/helpers/env-wrapper.ts(2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/providers/twitter/conversation.ts (4)
src/providers/twitter/graphql/request.ts (1)
graphqlRequest(25-38)src/providers/twitter/graphql/queries.ts (4)
TweetDetailQuery(50-105)TweetResultByRestIdQuery(3-48)TweetResultsByIdsQuery(107-143)TweetResultByIdQuery(145-181)src/helpers/graphql.ts (1)
isGraphQLTwitterStatus(15-23)src/experiments.ts (1)
experimentCheck(61-66)
🪛 Biome (1.9.4)
src/providers/twitter/conversation.ts
[error] 444-444: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
test/helpers/env-wrapper.ts
[error] 56-56: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🪛 GitHub Actions: Tests
src/providers/twitter/conversation.ts
[error] 346-418: Multiple 'TypeError: Cannot read properties of null (reading 'data')' errors in fetchSingleStatus and constructTwitterThread functions indicating null data handling issues.
test/helpers/env-wrapper.ts
[error] 67-67: Unknown error while fetching from API: 'Error: Invalid request' indicating API request failures.
[error] 26-26: Error loading mock: Unknown variable dynamic import for '../mocks/UserByScreenName/notfound3842342.json' causing test failure.
🔇 Additional comments (9)
test/helpers/env-wrapper.ts (1)
15-15: Improved error message for better debugging.Including the URL in the error message is a good improvement as it provides more context for debugging API request issues.
src/providers/twitter/conversation.ts (8)
8-9: Good import refactoring for better code organization.The imports for the GraphQL queries and request handling have been properly added, centralizing the GraphQL functionality.
45-67: Well-structured refactoring to use the GraphQL request system.The refactoring of
fetchTweetDetailto use the commongraphqlRequestfunction is a good improvement for code consistency and maintainability.🧰 Tools
🪛 ESLint
[error] 57-57: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
77-118: Clean implementation of fetchByRestId with proper validator.The refactoring of
fetchByRestIdwith comprehensive validation conditions is robust. The validator handles various error cases appropriately.
270-270: Good addition of conversation_id_str fallback for ID matching.Adding
conversation_id_stras a fallback for ID matching improves the robustness of tweet matching when standard IDs are not available.Also applies to: 276-276, 282-282
498-506: Well-implemented type guard for response verification.The type guard for TweetDetailResponse is a good pattern for ensuring type safety when working with multiple response formats.
623-623: Good ID resolution with additional fallback.Adding
conversation_id_stras a fallback ID provides more robust handling of Twitter's inconsistent ID field usage.
307-369:⚠️ Potential issueFix null handling in fetchSingleStatus function.
The weighted endpoint selection strategy is excellent, but the function has null handling issues that could be causing test failures.
The function needs to handle potential null data in the responses:
const fetchSingleStatus = async (id: string, c: Context): Promise<TweetResultsByRestIdResponse | TweetResultsByIdsResponse | null> => { // Weight calculations and endpoint selection remain the same try { if (random < normalizedWeights.TweetResultsByRestId) { console.log('Trying TweetResultsByRestId (weighted selection)...'); const response = await fetchByRestId(id, c); - if (response.data?.tweetResult?.result?.__typename) { + if (response?.data?.tweetResult?.result?.__typename) { console.log('Successfully fetched tweet using TweetResultsByRestId'); return response; } console.log('TweetResultsByRestId failed to return valid result'); } console.log('Trying TweetResultsByIds...'); const response = await fetchByIds([id], c); - if (response.data?.tweet_results?.[0]?.result?.__typename) { + if (response?.data?.tweet_results?.[0]?.result?.__typename) { console.log('Successfully fetched tweet using TweetResultsByIds'); return response; } console.log('TweetResultsByIds failed to return valid result'); // Only try again if we didn't already try the other endpoint if (random >= normalizedWeights.TweetResultsByRestId) { console.log('Trying TweetResultsByRestId as fallback...'); const response = await fetchByRestId(id, c); - if (response.data?.tweetResult?.result?.__typename) { + if (response?.data?.tweetResult?.result?.__typename) { console.log('Successfully fetched tweet using TweetResultsByRestId (fallback)'); return response; } console.log('TweetResultsByRestId fallback failed to return valid result'); } } catch (error) { console.error('Error fetching tweet:', error); } console.log('All endpoints failed to fetch tweet'); return null; }These changes ensure that we don't try to access properties on potentially null objects, addressing the pipeline failures.
Likely an incorrect or invalid review comment.
416-424:⚠️ Potential issueImplement consistent null handling when extracting tweet results.
There's inconsistent null checking when extracting tweet results from different response types.
Add consistent null checking to prevent "Cannot read properties of null" errors:
response = (await fetchSingleStatus(id, c)) as TweetResultsByIdsResponse; let result: GraphQLTwitterStatus | null = null; -if ((response as TweetResultsByRestIdResponse).data?.tweetResult?.result) { +if (response && (response as TweetResultsByRestIdResponse).data?.tweetResult?.result) { result = (response as TweetResultsByRestIdResponse).data?.tweetResult?.result as GraphQLTwitterStatus; -} else if ((response as TweetResultsByIdsResponse).data?.tweet_results?.[0]?.result) { +} else if (response && (response as TweetResultsByIdsResponse).data?.tweet_results?.[0]?.result) { result = (response as TweetResultsByIdsResponse).data?.tweet_results?.[0]?.result as GraphQLTwitterStatus; -} else if ((response as TweetResultByIdResponse).data?.tweet_result?.result) { +} else if (response && (response as TweetResultByIdResponse).data?.tweet_result?.result) { result = (response as TweetResultByIdResponse).data?.tweet_result?.result as GraphQLTwitterStatus; }This change ensures we check that
responseexists before trying to access properties on it, preventing the pipeline failures.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/providers/twitter/conversation.ts (1)
120-149: Good implementation of fetchByIds but validator could be improved.The new
fetchByIdsfunction is a valuable addition for fetching multiple tweets at once, but the validator doesn't handle as many error cases asfetchByRestId.Consider enhancing the validator to match the thoroughness of
fetchByRestId:validator: (_conversation: unknown) => { const conversation = _conversation as TweetResultsByIdsResponse; // If we get a not found error it's still a valid response const tweet = conversation.data?.tweet_results?.[0]?.result; console.log('result', conversation.data?.tweet_results?.[0]?.result); if (isGraphQLTwitterStatus(tweet)) { return true; } console.log('invalid graphql tweet'); + if ( + !tweet && + typeof conversation.data?.tweet_results === 'object' && + Object.keys(conversation.data?.tweet_results || {}).length === 0 + ) { + console.log('tweet was not found'); + return true; + } + if (tweet?.__typename === 'TweetUnavailable' && tweet.reason === 'NsfwLoggedOut') { + console.log('tweet is nsfw'); + return true; + } + if (tweet?.__typename === 'TweetUnavailable' && tweet.reason === 'Protected') { + console.log('tweet is protected'); + return true; + } + if (tweet?.__typename === 'TweetUnavailable') { + console.log('generic tweet unavailable error'); + return true; + } // Final clause for checking if it's valid is if there's errors return Array.isArray(conversation.errors);
🧹 Nitpick comments (3)
src/providers/twitter/conversation.ts (3)
307-369: Clever implementation of endpoint selection with weighted fallback.The weighted random selection between endpoints based on rate limits is an excellent approach to manage API usage efficiently. The implementation includes proper fallbacks and respects the Elongator experiment flag.
A few suggestions to enhance this function:
const fetchSingleStatus = async (id: string, c: Context): Promise<TweetResultsByRestIdResponse | TweetResultsByIdsResponse | null> => { // Weights determined by rate limit. We should use their weights to randomly determine which endpoint to first try // Otherwise we can fall back to the next endpoint // We will need to see if the tweet results exist and try the next endpoint if they don't const endpointWeights: Record<string, number> = { TweetResultsByRestId: 50, TweetResultsByIds: 500 } + + console.log('Attempting to fetch tweet with ID:', id); // Calculate total weight and normalized weights const totalWeight = Object.values(endpointWeights).reduce((sum, weight) => sum + weight, 0); const normalizedWeights = Object.entries(endpointWeights).reduce((acc, [key, weight]) => { acc[key] = weight / totalWeight; return acc; }, {} as Record<string, number>); // If we're not using Elongator, we are only able to use TweetResultsByRestId if (!experimentCheck(Experiment.ELONGATOR_BY_DEFAULT, typeof c.env?.TwitterProxy !== 'undefined')) { console.log('Elongator not available, using TweetResultsByRestId only'); normalizedWeights.TweetResultsByRestId = 1; normalizedWeights.TweetResultsByIds = 0; } const random = Math.random(); console.log('Random value:', random); console.log('Normalized weights:', normalizedWeights); try { if (random < normalizedWeights.TweetResultsByRestId) { console.log('Trying TweetResultsByRestId (weighted selection)...'); const response = await fetchByRestId(id, c); if (response?.data?.tweetResult?.result?.__typename) { console.log('Successfully fetched tweet using TweetResultsByRestId'); return response; } console.log('TweetResultsByRestId failed to return valid result'); } console.log('Trying TweetResultsByIds...'); const response = await fetchByIds([id], c); if (response?.data?.tweet_results?.[0]?.result?.__typename) { console.log('Successfully fetched tweet using TweetResultsByIds'); return response; } console.log('TweetResultsByIds failed to return valid result'); // Only try again if we didn't already try the other endpoint if (random >= normalizedWeights.TweetResultsByRestId) { console.log('Trying TweetResultsByRestId as fallback...'); const response = await fetchByRestId(id, c); if (response?.data?.tweetResult?.result?.__typename) { console.log('Successfully fetched tweet using TweetResultsByRestId (fallback)'); return response; } console.log('TweetResultsByRestId fallback failed to return valid result'); } } catch (error) { - console.error('Error fetching tweet:', error); + console.error(`Error fetching tweet ${id}:`, error instanceof Error ? error.message : error); } console.log('All endpoints failed to fetch tweet'); return null; }
383-457: Robust response type handling with appropriate fallbacks.Good job implementing comprehensive type detection and fallback mechanisms for the different GraphQL response formats. This provides much more resilient tweet fetching.
There's a static analysis hint suggesting a change to optional chaining at line 444:
- if (response && response.data) { + if (response?.data) {🧰 Tools
🪛 Biome (1.9.4)
[error] 444-444: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
587-587: Consider using more specific types for cursor responses.The
loadCursorvariables are typed asTweetDetailResponse, but it might be clearer to create a more specific type that indicates these are paginated responses.Also applies to: 651-651
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/providers/twitter/conversation.ts(14 hunks)src/providers/twitter/graphql/request.ts(1 hunks)test/helpers/env-wrapper.ts(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- test/helpers/env-wrapper.ts
- src/providers/twitter/graphql/request.ts
🧰 Additional context used
🪛 Biome (1.9.4)
src/providers/twitter/conversation.ts
[error] 444-444: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🔇 Additional comments (6)
src/providers/twitter/conversation.ts (6)
8-9: Clean imports for the new GraphQL approach.Good architectural decision to import query configurations from dedicated files rather than defining them inline. This makes the code more maintainable and testable.
45-68: Well-structured GraphQL request implementation.The function has been nicely refactored to use the new GraphQL request abstraction. The removal of the
useElongatorparameter simplifies the API while the GraphQL approach provides better type safety.🧰 Tools
🪛 ESLint
[error] 57-57: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
77-118: Good implementation of fetchByRestId with robust error handling.The validator function thoroughly handles different error cases and response types, making the function more resilient.
152-189: Good implementation of fetchById with appropriate error handling.The validator is well-implemented with robust error checking, though it doesn't handle the "Protected" case that exists in
fetchByRestId.
270-270: Robust ID fallback logic.Adding the
conversation_id_strfallback for tweet identification improves resilience when working with various Twitter API responses.Also applies to: 276-276, 282-282
497-499: Good type guard implementation.The type guard function has been properly updated to handle all the possible response types, which helps TypeScript properly narrow down the types.
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Tests