Repository navigation
feat(api): migrate GET /api/instagram/comments - #480
arpitgupta1214 wants to merge 1 commit into
Conversation
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>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (4)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
Preview smoke —
|
| 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.
There was a problem hiding this comment.
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.tstreats whitespace-onlypostUrlsas 500s instead of 400s, andlib/apify/instagram/validateGetInstagramCommentsRequest.tscurrently accepts malformedwebhooksentries due to permissivez.custom()usage. - The export-structure concern in
app/api/instagram/comments/route.tsis 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)
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); |
There was a problem hiding this comment.
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>
| const cleanUrls = postUrls.map(u => u.trim()).filter(u => u.length > 0); | ||
|
|
||
| if (cleanUrls.length === 0) { | ||
| throw new Error("Invalid Instagram post URLs"); |
There was a problem hiding this comment.
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>
| 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(), |
There was a problem hiding this comment.
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>
| @@ -0,0 +1,26 @@ | |||
| import { NextRequest, NextResponse } from "next/server"; | |||
There was a problem hiding this comment.
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>
|
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. |
Migrates the legacy Express
GET /api/instagram/commentsendpoint intomono/apias a flat Next.js route. Validator owns auth viavalidateAuthContext; handler returns{ runId, datasetId }for wire parity with the legacyApifyScraperResult. Webhook URL stays pointed atchat.recoupable.com/api/apifyper the migration plan.Test plan
postUrlspostUrls(returnsrunId+datasetId)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.
dynamic: "force-dynamic",maxDuration = 30(usesnext/server).postUrls(repeatable),resultsLimit(default 10000),isNewestComments,webhooks(base64 JSON array); 400 on invalid input.validateAuthContextenforces API key; 401 on failure.apify-client; returnsrunIdanddatasetId; masks internal errors.vitest.Written for commit 41b9221. Summary will update on new commits.