Skip to content

Improved graphql client - #1290

Merged
dangeredwolf merged 18 commits into
mainfrom
improved-graphql-client
Apr 29, 2025
Merged

dangeredwolf merged 18 commits into
mainfrom
improved-graphql-client

Conversation

@dangeredwolf

@dangeredwolf dangeredwolf commented Apr 29, 2025 •

Copy link
Copy Markdown
Member
  • Abstracts away complexities of GraphQL queries
  • We now use TweetResultsByIdsQuery which has much higher rate limit
  • Tests that hopefully work

Summary by CodeRabbit

  • New Features

    • Added support for additional Twitter GraphQL endpoints, improving reliability when fetching tweets and user profiles.
    • Enhanced thread construction and tweet fetching with improved fallback logic for tweet and user identifiers.
    • Introduced a unified GraphQL request module to streamline Twitter API interactions.
  • Bug Fixes

    • Improved robustness when extracting user and tweet IDs from Twitter API responses, reducing errors from missing or inconsistent data.
  • Refactor

    • Unified and streamlined Twitter GraphQL request handling for better maintainability and type safety.
    • Removed deprecated user fetching function in favor of GraphQL-based user queries.
  • Tests

    • Added new mock data files and test cases for expanded Twitter API coverage.
    • Enhanced error messages and mock handling for Twitter API methods.

@coderabbitai

coderabbitai Bot commented Apr 29, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 76e3074 and 7e8f54b.

📒 Files selected for processing (2)
  • .github/workflows/eslint.yml (0 hunks)
  • src/providers/twitter/conversation.ts (14 hunks)
📝 Walkthrough

Walkthrough

This 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 graphqlRequest function and predefined query objects. New response types and fallback mechanisms are implemented to robustly handle various Twitter API response structures. Additional fallbacks are added for tweet and user ID extraction. Several test mocks and supporting logic are added for new API endpoints. Some legacy or redundant code is removed, and type definitions are updated to reflect the new response formats and optional fields.

Changes

File(s) Change Summary
src/providers/twitter/graphql/queries.ts, src/providers/twitter/graphql/request.ts Introduced new modules defining standardized GraphQL query objects and a generic request function for Twitter GraphQL endpoints.
src/providers/twitter/conversation.ts Refactored tweet/thread fetching to use the new GraphQL request system, added weighted endpoint selection, improved type safety, and enhanced fallback logic for fetching tweets and constructing threads.
src/providers/twitter/fetch.ts Updated import paths, fixed type assertions, and removed the now-obsolete fetchUser function.
src/providers/twitter/profile.ts Switched to using the new graphqlRequest with UserByScreenNameQuery for user data fetching; updated validation logic.
src/providers/twitter/processor.ts Enhanced fallback logic for extracting user and tweet IDs from status objects.
src/helpers/translate.ts Added an extra fallback for tweet ID extraction when constructing translation API URLs.
src/types/vendor/twitter.d.ts Updated and renamed response types, added new types for multi-tweet responses, and made user result fields optional with new fallbacks.
src/embed/activity.ts Commented out a debug console.log statement.
test/helpers/env-wrapper.ts Added a new case to mock the TweetResultsByIds API method for testing.
test/mocks/TweetResultsByIds/*.json Added multiple detailed JSON mock files representing Twitter API responses for various tweet IDs.

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
Loading

Possibly related PRs

Poem

🐇
In burrows deep, I refactored with care,
GraphQL queries now float through the air.
With fallbacks and mocks, the tests all pass,
Types are robust, and bugs fewer at last.
From threads to users, the fetches are neat—
This rabbit’s code hop is agile and fleet!

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 under src/providers/twitter/graphql/, which means the GraphQL handler likely doesn’t use response.json() there—or that path is incorrect. To confirm the root cause of the “Unexpected end of JSON input” at line 164 in fetch.ts, can you help verify how that file handles empty or non-JSON responses? For example, does it guard on response.ok or check Content-Length before 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.ts

Length 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 issue

Null-safety: response can be null, causing the test failure

fetchSingleStatus explicitly returns null when all endpoints fail, yet the code dereferences response.data before 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 fetchSingleStatus is 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 via TweetResultById

filterBucketStatuses currently filters only on user_results.
Tweets fetched through TweetResultById / TweetResultsByIds may carry user_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_id parameter 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 import

The fetchUser import 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 probability

When Elongator is unavailable the weights are set to 1 and 0, but the earlier normalizedWeights
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

📥 Commits

Reviewing files that changed from the base of the PR and between 6474ab6 and 4c0cf11.

📒 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 || true

Length 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.ts

Length 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.ts

Length 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 || true

Length 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 || true

Length of output: 1521


Ignore missing ExecutionContext — handleActivity correctly uses Hono Context

After verifying constructTwitterThread, graphqlRequest, and handleActivity, there are no references to an ExecutionContext or waitUntil in these modules. The GraphQL response is validated in graphqlRequest via its validator callbacks, and handleActivity consumes the resulting SocialThread as expected. The reported error on line 262 is not caused by a missing ExecutionContext in 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_str as 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 TweetResultsByRestIdResult to TweetResultsByRestIdResponse ensures proper type checking with the updated type definitions.

src/providers/twitter/processor.ts (2)

54-54: Enhanced user extraction with fallback path

The implementation now handles multiple Twitter API response structures by adding a fallback path from user_results to user_result. This makes the code more robust against API variations.


58-58: Improved tweet ID extraction with multiple fallbacks

This change adds progressive fallbacks for tweet ID extraction: first trying rest_id, then legacy.id_str, and finally legacy?.conversation_id_str. This makes the code more resilient against inconsistent API responses.

The fallback to conversation_id_str is particularly useful as mentioned in the issue reference comment (line 57), protecting against undefined rest_id cases.

src/providers/twitter/profile.ts (2)

6-7: Added GraphQL infrastructure imports

These new imports support the refactored GraphQL request implementation, providing better abstraction for API queries.


92-104: Refactored user fetching to use GraphQL infrastructure

The implementation now leverages the new GraphQL infrastructure with several benefits:

  1. Uses standardized query definitions from a central location
  2. Adds explicit validation of response structure
  3. 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 __typename and the existence of required legacy data, ensuring robust error handling.

test/mocks/TweetResultsByIds/1902059299591090335.json (1)

1-399: Well-structured mock for TweetResultsByIds endpoint

This 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 tweet

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

Comment thread test/helpers/env-wrapper.ts Outdated
Comment on lines +55 to +65
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: {} }));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ 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.

Suggested change
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');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 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" | sort

Length 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 *.json to test/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

Comment thread test/helpers/env-wrapper.ts Resolved
Comment on lines +399 to 405
user_results?: {
result: GraphQLUser;
};
user_result?: {
result: GraphQLUser;
};
};

@coderabbitai coderabbitai Bot Apr 29, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

  1. 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;
}
  1. 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
test/helpers/env-wrapper.ts (1)

55-65: ⚠️ Potential issue

Fix variable scope in switch case and update to handle array rest_ids.

The new TweetResultsByIds case has two issues:

  1. The tweetIds variable declaration has a static analysis warning about scope - it should be wrapped in a block
  2. It uses variables.tweetIds but the GraphQL query actually passes variables.rest_ids as an array

Apply 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 response includes 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4c0cf11 and 018f5b6.

📒 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 fetchTweetDetail to use the common graphqlRequest function 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 fetchByRestId with 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_str as 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_str as a fallback ID provides more robust handling of Twitter's inconsistent ID field usage.


307-369: ⚠️ Potential issue

Fix 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 issue

Implement 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 response exists before trying to access properties on it, preventing the pipeline failures.

Likely an incorrect or invalid review comment.

Comment thread src/providers/twitter/conversation.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
src/providers/twitter/conversation.ts (1)

120-149: Good implementation of fetchByIds but validator could be improved.

The new fetchByIds function is a valuable addition for fetching multiple tweets at once, but the validator doesn't handle as many error cases as fetchByRestId.

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 loadCursor variables are typed as TweetDetailResponse, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 018f5b6 and 76e3074.

📒 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 useElongator parameter 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_str fallback 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.

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.

1 participant