Repository navigation
feat: twitter search api - #1852
Conversation
|
Caution Review failedPull request was closed or merged during review No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds a GraphQL-based Twitter search flow: new SearchTimelineQuery and search provider, timeline instruction types replaced with a discriminated union, conversation processing updated to accept Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant Router as Router
participant Handler as Handler
participant Provider as SearchProvider
participant GraphQL as GraphQL
participant Processor as Processor
Client->>Router: GET /2/search?q=...&feed=...&count=...&cursor=...
Router->>Handler: route to searchAPIRequest
Handler->>Handler: validate & parse params
Handler->>Provider: searchAPI(query, feed, count, cursor, c)
Provider->>GraphQL: execute SearchTimelineQuery (GET)
GraphQL-->>Provider: timeline (TimelineInstruction[])
Provider->>Processor: processSearchInstructions(instructions)
Processor-->>Provider: statuses + cursors
Provider-->>Handler: APISearchResults (code, results, cursor)
Handler->>Client: HTTP response (status, body)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (3)
src/providers/twitter/search.ts (2)
154-157: Simplify Promise creation.
new Promise(resolve => resolve(null))can be simplified toPromise.resolve(null).♻️ Proposed fix
} catch (e) { console.error('Error building status', e); - return new Promise(resolve => resolve(null)); + return Promise.resolve(null); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/search.ts` around lines 154 - 157, The catch block in the status-building code currently returns a manually created promise via new Promise(resolve => resolve(null)); simplify this by returning Promise.resolve(null) instead; locate the catch in the status builder (the catch handling errors while building status in src/providers/twitter/search.ts, e.g., the catch block that logs "Error building status") and replace the manual Promise construction with Promise.resolve(null) to make the code clearer and more concise.
132-132: Consider removing or reducing verbose response logging.Logging the entire GraphQL response with
JSON.stringify(response)may include user data (tweet content, usernames) in production logs. Consider removing this or logging only essential debug information.🔒 Proposed fix
- console.log('response', JSON.stringify(response)); + // console.log('response', JSON.stringify(response)); // Enable for debugging only🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/search.ts` at line 132, Remove the verbose console.log call that prints the full GraphQL response (the line console.log('response', JSON.stringify(response))) to avoid leaking user data; either delete it or replace it with a safe, minimal log (e.g., log a summary like response.status, response.meta, or the count of items) or use a debug-level logger that only runs when a debug flag is enabled and redacts sensitive fields (tweet text, usernames, ids) before logging.src/types/vendor/twitter.d.ts (1)
703-721: Consider addingTimelineReplaceEntryto the union.The
TimelineInstructionunion may be incomplete for search API responses. The code insrc/providers/twitter/search.tshandles aTimelineReplaceEntryinstruction type for cursor updates during pagination, but this type is not defined in the union.If Twitter's search API returns this instruction type, consider adding it:
♻️ Proposed addition
type TimelineInstruction = | TimelineAddEntriesInstruction | TimelineTerminateTimelineInstruction - | TimelineAddModulesInstruction; + | TimelineAddModulesInstruction + | TimelineReplaceEntryInstruction; +type TimelineReplaceEntryInstruction = { + type: 'TimelineReplaceEntry'; + entry: { + content: GraphQLTimelineCursor; + }; +};🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/types/vendor/twitter.d.ts` around lines 703 - 721, Add a new TimelineReplaceEntry instruction type and include it in the TimelineInstruction union: define a TimelineReplaceEntryInstruction type with type: 'TimelineReplaceEntry' and fields matching how src/providers/twitter/search.ts reads cursor updates (e.g., the entry payload/key(s) used for pagination such as cursor/entryId/moduleItems or similar), then add TimelineReplaceEntryInstruction to the union alongside TimelineAddEntriesInstruction, TimelineAddModulesInstruction, and TimelineTerminateTimelineInstruction so the type definitions align with the code that expects 'TimelineReplaceEntry'.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/twitter/conversation.ts`:
- Around line 314-324: The code reads entryType from
content.itemContent?.tweet_results.result?.__typename but then pushes
content.itemContent?.tweet_results.result (or .result.tweet) without verifying
result exists, which can add undefined to bucket.statuses; modify the logic in
the block around entryType to first capture const result =
content.itemContent?.tweet_results.result and if (result) { if (entryType ===
'Tweet') bucket.statuses.push(result as GraphQLTwitterStatus); if (entryType ===
'TweetWithVisibilityResults' && result.tweet) bucket.statuses.push(result.tweet
as GraphQLTwitterStatus); } so you only push when result (and result.tweet) are
defined.
In `@src/providers/twitter/graphql/queries.ts`:
- Line 351: Remove the trailing comma after the querySource property in the
object literal (the line containing "querySource: 'typed_query'") so the
property is the last entry without a comma; update the object in the GraphQL
queries file where querySource is defined (search for the querySource property
in the queries.ts snippet) to satisfy ESLint formatting rules.
In `@src/providers/twitter/search.ts`:
- Around line 42-57: The branch checking for instruction.type ===
'TimelineReplaceEntry' inside the instructions?.forEach (the instruction
variable in src/providers/twitter/search.ts) is dead because
TimelineReplaceEntry is not part of the TimelineInstruction union in
src/types/vendor/twitter.d.ts; fix by either removing this unreachable block
(delete the TimelineReplaceEntry check and its cursor-pushing logic) or add a
proper TimelineReplaceEntry variant to the TimelineInstruction union in
src/types/vendor/twitter.d.ts (model the new type to include entry?: { content?:
{ __typename: 'TimelineTimelineCursor'; /* cursor fields */ } } so the existing
code can type-check and push cursors correctly).
In `@src/types/types.d.ts`:
- Line 337: The interfaces ActivityStatus, ActivityAccount, and
ActivityMediaAttachment are missing the export keyword which breaks TypeScript
imports; fix by updating their declarations in types.d.ts to be exported (e.g.,
change the declarations for ActivityStatus, ActivityAccount, and
ActivityMediaAttachment to use "export interface ...") and ensure the export
style matches other exported types in the file so imports in
src/embed/activity.ts and test/activity.test.ts resolve correctly.
---
Nitpick comments:
In `@src/providers/twitter/search.ts`:
- Around line 154-157: The catch block in the status-building code currently
returns a manually created promise via new Promise(resolve => resolve(null));
simplify this by returning Promise.resolve(null) instead; locate the catch in
the status builder (the catch handling errors while building status in
src/providers/twitter/search.ts, e.g., the catch block that logs "Error building
status") and replace the manual Promise construction with Promise.resolve(null)
to make the code clearer and more concise.
- Line 132: Remove the verbose console.log call that prints the full GraphQL
response (the line console.log('response', JSON.stringify(response))) to avoid
leaking user data; either delete it or replace it with a safe, minimal log
(e.g., log a summary like response.status, response.meta, or the count of items)
or use a debug-level logger that only runs when a debug flag is enabled and
redacts sensitive fields (tweet text, usernames, ids) before logging.
In `@src/types/vendor/twitter.d.ts`:
- Around line 703-721: Add a new TimelineReplaceEntry instruction type and
include it in the TimelineInstruction union: define a
TimelineReplaceEntryInstruction type with type: 'TimelineReplaceEntry' and
fields matching how src/providers/twitter/search.ts reads cursor updates (e.g.,
the entry payload/key(s) used for pagination such as cursor/entryId/moduleItems
or similar), then add TimelineReplaceEntryInstruction to the union alongside
TimelineAddEntriesInstruction, TimelineAddModulesInstruction, and
TimelineTerminateTimelineInstruction so the type definitions align with the code
that expects 'TimelineReplaceEntry'.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 147ceafa-002f-4671-98b6-23fb30838f28
📒 Files selected for processing (7)
src/providers/twitter/conversation.tssrc/providers/twitter/graphql/queries.tssrc/providers/twitter/search.tssrc/realms/api/router.tssrc/realms/api/routes/twitter.tssrc/types/types.d.tssrc/types/vendor/twitter.d.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
test/api.search.test.ts (1)
43-70: Tests verify parameter acceptance but not behavioral effect.Both tests confirm the endpoint accepts
feedandcountparameters without error, but they don't verify these parameters influence the response. Since the harness returns identical mock data regardless of parameter values, distinguishing behavior would require either:
- Multiple mocks keyed by the
productvariable (derived fromfeed)- Asserting
response.results.length <= countwhen count is passedThis is fine as acceptance tests, but consider expanding coverage later to validate parameter effects end-to-end.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/api.search.test.ts` around lines 43 - 70, The tests "API search accepts feed parameter" and "API search accepts count parameter" only check acceptance; update them to verify behavior: for the count test (test name "API search accepts count parameter") assert that response.results.length is <= the requested count (e.g., 10) and/or exactly equals when your mock supports that; for the feed test (test name "API search accepts feed parameter") either make the harness return different mock responses keyed by the product variable (derived from the feed query) so you can assert different response contents for feed=top vs feed=latest, or assert that the returned response matches the specific mock tied to product; reference APISearchResults, harness and the product variable when implementing these assertions or mock-keying changes.test/helpers/harness.ts (1)
105-122: Static analysis flags unscoped switch declarations, but this follows existing file patterns.Biome correctly identifies that
rawQueryandsearchFilenameare declared without block scope (lines 106-107). However, all other cases in this switch (lines 23, 34, 45, 56, etc.) use the same pattern. While wrapping the case body in braces{ }would be cleaner, refactoring should apply to all cases for consistency rather than just this one.The fallback response structure correctly matches the expected path
data.search_by_raw_query.search_timeline.timeline.instructionsas validated by the search provider.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/helpers/harness.ts` around lines 105 - 122, The switch case 'SearchTimeline' declares rawQuery and searchFilename without block scope which triggers static analysis; wrap the case body in braces (i.e., case 'SearchTimeline': { ... } break;) so rawQuery and searchFilename are block-scoped, and apply the same bracing pattern consistently to the other switch cases in this file (refer to the variables rawQuery and searchFilename and the case 'SearchTimeline' in test/helpers/harness.ts) to keep declarations scoped and satisfy the linter.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@test/api.search.test.ts`:
- Around line 43-70: The tests "API search accepts feed parameter" and "API
search accepts count parameter" only check acceptance; update them to verify
behavior: for the count test (test name "API search accepts count parameter")
assert that response.results.length is <= the requested count (e.g., 10) and/or
exactly equals when your mock supports that; for the feed test (test name "API
search accepts feed parameter") either make the harness return different mock
responses keyed by the product variable (derived from the feed query) so you can
assert different response contents for feed=top vs feed=latest, or assert that
the returned response matches the specific mock tied to product; reference
APISearchResults, harness and the product variable when implementing these
assertions or mock-keying changes.
In `@test/helpers/harness.ts`:
- Around line 105-122: The switch case 'SearchTimeline' declares rawQuery and
searchFilename without block scope which triggers static analysis; wrap the case
body in braces (i.e., case 'SearchTimeline': { ... } break;) so rawQuery and
searchFilename are block-scoped, and apply the same bracing pattern consistently
to the other switch cases in this file (refer to the variables rawQuery and
searchFilename and the case 'SearchTimeline' in test/helpers/harness.ts) to keep
declarations scoped and satisfy the linter.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 188ede24-35c1-44b6-bc86-7097a65bdf2e
📒 Files selected for processing (4)
src/providers/twitter/search.tstest/api.search.test.tstest/helpers/harness.tstest/mocks/SearchTimeline/neo.json
🚧 Files skipped from review as they are similar to previous changes (1)
- src/providers/twitter/search.ts
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/providers/twitter/search.ts (3)
146-149: Simplify promise creation.
new Promise(resolve => resolve(null))can be replaced withPromise.resolve(null).♻️ Simplified fix
} catch (e) { console.error('Error building status', e); - return new Promise(resolve => resolve(null)); + return Promise.resolve(null); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/search.ts` around lines 146 - 149, In the catch block that logs "Error building status" (inside the function that builds statuses in src/providers/twitter/search.ts, e.g., buildStatus or the function wrapping that console.error), replace the manual promise creation new Promise(resolve => resolve(null)) with the simpler Promise.resolve(null); this reduces allocation and expresses intent directly.
77-80: Consider adding a type guard to avoidas unknown asdouble-cast.The double cast through
unknownsuggests the type definitions don't fully capture this code path. A type guard would be safer and more self-documenting.♻️ Suggested type guard
+const isTimelineCursor = (content: unknown): content is GraphQLTimelineCursor => + (content as GraphQLTimelineCursor)?.__typename === 'TimelineTimelineCursor'; // In the forEach: -} else if (content.__typename === 'TimelineTimelineCursor') { - // In search timeline, cursors appear directly as entry content rather than - // nested inside a TimelineTimelineItem wrapper as seen in TweetDetail - cursors.push(content as unknown as GraphQLTimelineCursor); +} else if (isTimelineCursor(content)) { + // In search timeline, cursors appear directly as entry content rather than + // nested inside a TimelineTimelineItem wrapper as seen in TweetDetail + cursors.push(content);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/search.ts` around lines 77 - 80, Replace the unsafe double-cast by implementing a type guard that checks content.__typename === 'TimelineTimelineCursor' and narrows content to GraphQLTimelineCursor before pushing; create a predicate function (e.g., isGraphQLTimelineCursor(obj): obj is GraphQLTimelineCursor) and use it in the branch that currently does cursors.push(content as unknown as GraphQLTimelineCursor) so the compiler understands the type without casting and the intent is documented.
137-138: Variablecshadows the outerContextparameter.The callback parameter
cincursors.find(c => ...)shadows thec: Contextfrom line 105. While this works, it reduces readability.♻️ Rename the callback parameter
- const topCursor = cursors.find(c => c.cursorType === 'Top')?.value ?? null; - const bottomCursor = cursors.find(c => c.cursorType === 'Bottom')?.value ?? null; + const topCursor = cursors.find(cursor => cursor.cursorType === 'Top')?.value ?? null; + const bottomCursor = cursors.find(cursor => cursor.cursorType === 'Bottom')?.value ?? null;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/search.ts` around lines 137 - 138, The callback parameter in the cursors.find calls shadows the outer Context parameter named `c`; rename the inner parameter to a descriptive name (e.g., `cursor` or `cur`) in both expressions that compute `topCursor` and `bottomCursor` so the code reads `cursors.find(cursor => cursor.cursorType === 'Top')` and `cursors.find(cursor => cursor.cursorType === 'Bottom')`, preserving the existing null coalescing behavior and avoiding shadowing of the `c: Context` variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/providers/twitter/search.ts`:
- Around line 146-149: In the catch block that logs "Error building status"
(inside the function that builds statuses in src/providers/twitter/search.ts,
e.g., buildStatus or the function wrapping that console.error), replace the
manual promise creation new Promise(resolve => resolve(null)) with the simpler
Promise.resolve(null); this reduces allocation and expresses intent directly.
- Around line 77-80: Replace the unsafe double-cast by implementing a type guard
that checks content.__typename === 'TimelineTimelineCursor' and narrows content
to GraphQLTimelineCursor before pushing; create a predicate function (e.g.,
isGraphQLTimelineCursor(obj): obj is GraphQLTimelineCursor) and use it in the
branch that currently does cursors.push(content as unknown as
GraphQLTimelineCursor) so the compiler understands the type without casting and
the intent is documented.
- Around line 137-138: The callback parameter in the cursors.find calls shadows
the outer Context parameter named `c`; rename the inner parameter to a
descriptive name (e.g., `cursor` or `cur`) in both expressions that compute
`topCursor` and `bottomCursor` so the code reads `cursors.find(cursor =>
cursor.cursorType === 'Top')` and `cursors.find(cursor => cursor.cursorType ===
'Bottom')`, preserving the existing null coalescing behavior and avoiding
shadowing of the `c: Context` variable.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: ef6619aa-9634-4413-bd7d-1af8b19df776
📒 Files selected for processing (2)
src/providers/twitter/search.tssrc/types/vendor/twitter.d.ts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/providers/twitter/conversation.ts (1)
291-301: 🛠️ Refactor suggestion | 🟠 MajorReplace
@ts-expect-errorwith explicit discriminated union narrowing.Using
@ts-expect-errorto suppress type checking here masks a real limitation in how TypeScript narrows the discriminated union. Explicit property access after type narrowing is the cleaner, safer approach that maintains type safety. Also add a default parameter to handle undefined gracefully at the call site.♻️ Proposed refactor
-const processResponse = (instructions: TimelineInstruction[]): GraphQLProcessBucket => { +const processResponse = (instructions: TimelineInstruction[] = []): GraphQLProcessBucket => { const bucket: GraphQLProcessBucket = { statuses: [], allStatuses: [], cursors: [] }; - instructions?.forEach?.(instruction => { - if (instruction.type === 'TimelineAddEntries' || instruction.type === 'TimelineAddToModule') { - // `@ts-expect-error` Use entries or moduleItems depending on the type - (instruction?.entries ?? instruction?.moduleItems)?.forEach(_entry => { + instructions.forEach(instruction => { + const entries = + instruction.type === 'TimelineAddEntries' + ? instruction.entries + : instruction.type === 'TimelineAddToModule' + ? instruction.moduleItems + : null; + if (!entries) return; + entries.forEach(_entry => { const entry = _entry as | GraphQLTimelineTweetEntry | GraphQLConversationThread | GraphQLModuleTweetEntry; const content = (entry as GraphQLModuleTweetEntry)?.item ?? (entry as GraphQLTimelineTweetEntry)?.content; @@ - }); - } + }); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/conversation.ts` around lines 291 - 301, The code uses `@ts-expect-error` to access either entries or moduleItems on TimelineInstruction; instead, update processResponse to explicitly narrow the discriminated union by checking instruction.type (e.g., in the branch for 'TimelineAddEntries' access instruction.entries, and in the 'TimelineAddToModule' branch access instruction.moduleItems) before iterating, removing the `@ts-expect-error`; also add a default parameter for instructions (e.g., instructions: TimelineInstruction[] = []) or guard at the top so undefined is handled safely; refer to the function processResponse and the TimelineInstruction/GraphQLProcessBucket symbols when making these changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@src/providers/twitter/conversation.ts`:
- Around line 291-301: The code uses `@ts-expect-error` to access either entries
or moduleItems on TimelineInstruction; instead, update processResponse to
explicitly narrow the discriminated union by checking instruction.type (e.g., in
the branch for 'TimelineAddEntries' access instruction.entries, and in the
'TimelineAddToModule' branch access instruction.moduleItems) before iterating,
removing the `@ts-expect-error`; also add a default parameter for instructions
(e.g., instructions: TimelineInstruction[] = []) or guard at the top so
undefined is handled safely; refer to the function processResponse and the
TimelineInstruction/GraphQLProcessBucket symbols when making these changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 10872202-9fdd-470f-b040-17ca5604ddfd
📒 Files selected for processing (1)
src/providers/twitter/conversation.ts
Summary by CodeRabbit
New Features
Bug Fixes / Improvements
Tests