Skip to content

feat(api): migrate GET /api/instagram/comments - #480

Closed
arpitgupta1214 wants to merge 1 commit into
testfrom
migrate/get-instagram-comments
Closed

arpitgupta1214 wants to merge 1 commit into
testfrom
migrate/get-instagram-comments

Conversation

@arpitgupta1214

@arpitgupta1214 arpitgupta1214 commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator

Migrates the legacy Express GET /api/instagram/comments endpoint into mono/api as a flat Next.js route. Validator owns auth via validateAuthContext; handler returns { runId, datasetId } for wire parity with the legacy ApifyScraperResult. Webhook URL stays pointed at chat.recoupable.com/api/apify per the migration plan.

Test plan

  • 401 on Vercel preview without auth
  • 400 on Vercel preview without postUrls
  • 200 on Vercel preview with valid postUrls (returns runId + datasetId)
  • Unit tests (handler + validator) green

Summary by cubic

Migrated the legacy Express GET /api/instagram/comments to a flat Next.js route. Preserves the response shape ({ runId, datasetId}) and keeps the webhook target at chat.recoupable.com/api/apify, while adding validation, auth, and safer errors.

  • New Features
    • Route: GET /api/instagram/comments with CORS preflight, dynamic: "force-dynamic", maxDuration = 30 (uses next/server).
    • Validation: supports postUrls (repeatable), resultsLimit (default 10000), isNewestComments, webhooks (base64 JSON array); 400 on invalid input.
    • Auth: validateAuthContext enforces API key; 401 on failure.
    • Scraping: starts Instagram Comments actor via apify-client; returns runId and datasetId; masks internal errors.
    • Tests: unit tests for handler and validator using vitest.

Written for commit 41b9221. Summary will update on new commits.

Port the legacy Express endpoint into mono/api as a flat Next.js route.
Validator owns auth via validateAuthContext; handler returns {runId, datasetId}
(wire parity with legacy ApifyScraperResult). Webhook URL remains pointed at
chat.recoupable.com/api/apify per the migration plan.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@vercel

vercel Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
api Ready Ready Preview Apr 24, 2026 6:21pm

Request Review

@coderabbitai

coderabbitai Bot commented Apr 24, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@arpitgupta1214 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 34 minutes and 51 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 34 minutes and 51 seconds.

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9bda4ae4-6f1a-4f1d-a0e3-84ccc8b106dd

📥 Commits

Reviewing files that changed from the base of the PR and between 4be1851 and 41b9221.

⛔ Files ignored due to path filters (2)
  • lib/apify/instagram/__tests__/getInstagramCommentsHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/apify/instagram/__tests__/validateGetInstagramCommentsRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (4)
  • app/api/instagram/comments/route.ts
  • lib/apify/instagram/getInstagramCommentsHandler.ts
  • lib/apify/instagram/startInstagramCommentsScraping.ts
  • lib/apify/instagram/validateGetInstagramCommentsRequest.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch migrate/get-instagram-comments

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@arpitgupta1214

Copy link
Copy Markdown
Collaborator Author

Preview smoke — api-git-migrate-get-instagram-comments-recoupable-ad724970.vercel.app

Probe Expected Actual Body
GET /api/instagram/comments (no auth) 401 401 {"status":"error","error":"Exactly one of x-api-key or Authorization must be provided"}
GET /api/instagram/comments + x-api-key 400 400 {"status":"error","error":"postUrls must include at least one value"}
GET /api/instagram/comments?postUrls=...&resultsLimit=5 + x-api-key 200 {runId,datasetId} 200 {"runId":"BBH64ANfcJmAoHFHp","datasetId":"7g476CYhlynsgx7Wg"}

The recoup-api-*.vercel.app alias is not wired for this preview branch (DNS no-host); only the api-*.vercel.app preview host exists at PR time. Post-merge promotion to test republishes to both production aliases.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

4 issues found across 6 files

Confidence score: 3/5

  • There is a concrete regression risk in app/api/instagram/comments/route.ts: the scraping endpoint is missing required rate-limiting enforcement, which can enable abuse and inconsistent API behavior.
  • Input validation has meaningful gaps: lib/apify/instagram/startInstagramCommentsScraping.ts treats whitespace-only postUrls as 500s instead of 400s, and lib/apify/instagram/validateGetInstagramCommentsRequest.ts currently accepts malformed webhooks entries due to permissive z.custom() usage.
  • The export-structure concern in app/api/instagram/comments/route.ts is lower severity and mostly maintainability-focused, so it is less likely to be merge-blocking on its own.
  • Pay close attention to app/api/instagram/comments/route.ts, lib/apify/instagram/startInstagramCommentsScraping.ts, lib/apify/instagram/validateGetInstagramCommentsRequest.ts - enforce rate limiting and tighten request validation/error mapping before merge.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="app/api/instagram/comments/route.ts">

<violation number="1" location="app/api/instagram/comments/route.ts:13">
P3: Custom agent: **Module should export a single primary function whose name matches the filename**

route.ts exports multiple top-level functions and does not have a single primary export named `route`, violating the module naming rule.</violation>

<violation number="2" location="app/api/instagram/comments/route.ts:25">
P1: Custom agent: **API Design Consistency and Maintainability**

Scraping endpoint lacks rate-limiting enforcement even though the API rule requires rate limiting for abuse prevention.</violation>
</file>

<file name="lib/apify/instagram/startInstagramCommentsScraping.ts">

<violation number="1" location="lib/apify/instagram/startInstagramCommentsScraping.ts:25">
P2: Whitespace-only `postUrls` values are treated as server errors (500) instead of request validation errors (400).</violation>
</file>

<file name="lib/apify/instagram/validateGetInstagramCommentsRequest.ts">

<violation number="1" location="lib/apify/instagram/validateGetInstagramCommentsRequest.ts:11">
P2: `webhooks` items are not actually validated: `z.custom()` without a predicate accepts any value. Add a runtime predicate/schema so malformed webhook entries are rejected at request validation time.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client as Client (Browser/App)
    participant Route as Route (app/api/...)
    participant Handler as Handler & Validator
    participant Auth as validateAuthContext
    participant Apify as Apify API (External)
    participant WebhookTarget as Webhook (chat.recoupable.com)

    Note over Client,WebHookTarget: NEW: Instagram Comments Migration Flow

    Client->>Route: GET /api/instagram/comments?postUrls=...
    Route->>Handler: getInstagramCommentsHandler(request)
    
    Handler->>Auth: NEW: validateAuthContext(request)
    alt 401 Unauthorized
        Auth-->>Handler: NextResponse(401)
        Handler-->>Client: 401 Unauthorized
    else Authorized
        Auth-->>Handler: AuthContext (accountId)
    end

    Handler->>Handler: NEW: validateGetInstagramCommentsRequest()
    Note right of Handler: Validates postUrls, resultsLimit,<br/>and decodes base64 webhooks.
    
    alt 400 Bad Request
        Handler-->>Client: 400 Invalid query parameters
    end

    Handler->>Apify: NEW: actor("SbK00X0JYCPblD2wp").start(input, { webhooks })
    
    alt Apify Success
        Apify-->>Handler: { id, defaultDatasetId }
        Handler-->>Client: 200 { runId, datasetId }
        Note over Client,Apify: CHANGED: Wire parity with legacy ApifyScraperResult
    else Apify Error / Timeout
        Apify-->>Handler: Error / null
        Handler->>Handler: Internal Error Logging
        Handler-->>Client: 500 Internal server error (Masked)
    end

    Note over Apify,WebhookTarget: Async Processing
    Apify-->>WebhookTarget: POST /api/apify (Results ready)
Loading

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

* @returns JSON with `{ runId, datasetId }` on success (wire parity with legacy ApifyScraperResult).
*/
export async function GET(request: NextRequest) {
return getInstagramCommentsHandler(request);

@cubic-dev-ai cubic-dev-ai Bot Apr 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: Custom agent: API Design Consistency and Maintainability

Scraping endpoint lacks rate-limiting enforcement even though the API rule requires rate limiting for abuse prevention.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/api/instagram/comments/route.ts, line 25:

<comment>Scraping endpoint lacks rate-limiting enforcement even though the API rule requires rate limiting for abuse prevention.</comment>

<file context>
@@ -0,0 +1,26 @@
+ * @returns JSON with `{ runId, datasetId }` on success (wire parity with legacy ApifyScraperResult).
+ */
+export async function GET(request: NextRequest) {
+  return getInstagramCommentsHandler(request);
+}
</file context>
Fix with Cubic

const cleanUrls = postUrls.map(u => u.trim()).filter(u => u.length > 0);

if (cleanUrls.length === 0) {
throw new Error("Invalid Instagram post URLs");

@cubic-dev-ai cubic-dev-ai Bot Apr 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Whitespace-only postUrls values are treated as server errors (500) instead of request validation errors (400).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/apify/instagram/startInstagramCommentsScraping.ts, line 25:

<comment>Whitespace-only `postUrls` values are treated as server errors (500) instead of request validation errors (400).</comment>

<file context>
@@ -0,0 +1,48 @@
+  const cleanUrls = postUrls.map(u => u.trim()).filter(u => u.length > 0);
+
+  if (cleanUrls.length === 0) {
+    throw new Error("Invalid Instagram post URLs");
+  }
+
</file context>
Fix with Cubic

postUrls: z.array(z.string().min(1)).min(1, "postUrls must include at least one value"),
resultsLimit: z.coerce.number().int().positive().optional().default(10000),
isNewestComments: z.boolean().optional(),
webhooks: z.array(z.custom<WebhookUpdateData>()).optional(),

@cubic-dev-ai cubic-dev-ai Bot Apr 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: webhooks items are not actually validated: z.custom() without a predicate accepts any value. Add a runtime predicate/schema so malformed webhook entries are rejected at request validation time.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/apify/instagram/validateGetInstagramCommentsRequest.ts, line 11:

<comment>`webhooks` items are not actually validated: `z.custom()` without a predicate accepts any value. Add a runtime predicate/schema so malformed webhook entries are rejected at request validation time.</comment>

<file context>
@@ -0,0 +1,64 @@
+  postUrls: z.array(z.string().min(1)).min(1, "postUrls must include at least one value"),
+  resultsLimit: z.coerce.number().int().positive().optional().default(10000),
+  isNewestComments: z.boolean().optional(),
+  webhooks: z.array(z.custom<WebhookUpdateData>()).optional(),
+});
+
</file context>
Fix with Cubic

@@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from "next/server";

@cubic-dev-ai cubic-dev-ai Bot Apr 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Custom agent: Module should export a single primary function whose name matches the filename

route.ts exports multiple top-level functions and does not have a single primary export named route, violating the module naming rule.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/api/instagram/comments/route.ts, line 13:

<comment>route.ts exports multiple top-level functions and does not have a single primary export named `route`, violating the module naming rule.</comment>

<file context>
@@ -0,0 +1,26 @@
+ *
+ * @returns 200 response with CORS headers.
+ */
+export async function OPTIONS() {
+  return new NextResponse(null, { status: 200, headers: getCorsHeaders() });
+}
</file context>
Fix with Cubic

@arpitgupta1214

Copy link
Copy Markdown
Collaborator Author

Closing — strategy revised. Instagram scrape endpoints will not be public HTTP routes. Instead, chat's Apify webhook is moving into mono/api and will invoke startInstagramCommentsScraping / startInstagramProfileScraping as in-process functions. See revised AGENT_API_MIGRATION_PLAN.md.

This branch was successfully deployed

1 active deployment
Preview — 41b92218 Deployed Apr 24, 2026 by vercel[bot]
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