Skip to content

create and update the main API Route#14

Merged
naheel0 merged 4 commits intomainfrom
router
Feb 9, 2026
Merged

create and update the main API Route#14
naheel0 merged 4 commits intomainfrom
router

Conversation

@naheel0
Copy link
Contributor

@naheel0 naheel0 commented Feb 9, 2026

🚀 BΞYTΞFLʘW | Pull Request Protocol

PR Type: (Choose one: feat | fix | refactor | docs | perf)
Issue Link: Fixes #


📝 System Summary

Provide a concise brief of the changes introduced to the stream.

🛠️ Technical Changes

  • Logic change in ...
  • New UI component added: ...
  • Database schema updated: ...

🧪 Quality Assurance (QA)

  • Linting: Code style matches the BeyteFlow grid.
  • Build: npm run build executed without errors.
  • Testing: New logic has been verified and tested.
  • Dark Mode: UI is high-contrast and neon-optimized.

🖼️ Visual Evidence

If this PR affects the UI, drop a screenshot or GIF below:


📡 Developer Authorization

  • I have performed a self-review of my code.
  • My changes generate no new warnings in the console.
  • I have updated the documentation (if applicable).

Authorized by: @naheel0 @adithyanmkd
Timestamp: {{ 9/2/2026 }}


Co-Authored-By: Adithyan <100783336+adithyanmkd@users.noreply.github.com>
@naheel0 naheel0 requested a review from adithyanmkd as a code owner February 9, 2026 09:52
@naheel0 naheel0 added area: ai-logic Related to Gemini prompts, tokens, or model responses. area: backend Related to Next.js API routes or Octokit/GitHub API. labels Feb 9, 2026
@vercel
Copy link

vercel bot commented Feb 9, 2026

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

Project Deployment Actions Updated (UTC)
readme-gen-ai Ready Ready Preview, Comment Feb 9, 2026 10:07am

@coderabbitai
Copy link

coderabbitai bot commented Feb 9, 2026

Warning

Rate limit exceeded

@naheel0 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 12 minutes and 39 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.

📝 Walkthrough

Walkthrough

A new API endpoint for generating README files has been implemented. It validates GitHub URLs, fetches repository metadata and contents concurrently, constructs a detailed prompt for Gemini AI to generate comprehensive README documentation with sections for features, installation, and usage, and returns the generated markdown. Supporting library functions fetch repository contents via Octokit.

Changes

Cohort / File(s) Summary
README Generation Endpoint
src/app/api/generate/route.ts
New POST endpoint that validates GitHub URLs, parses owner/repo, fetches metadata and contents concurrently, generates README via Gemini with conditional installation steps, and returns markdown. Includes input validation (400) and error handling (500).
Repository Content Fetching
src/lib/octokit.ts
Added getRepoContents(owner, repo) function to fetch root directory contents via Octokit. Updated getRepoData error message for clarity. Both functions return empty array on failure.
TypeScript Configuration
tsconfig.json
Updated path resolution: added baseUrl: "." and changed @/* path mapping from "./*" to "./src/*".

Sequence Diagram

sequenceDiagram
    participant Client
    participant APIRoute as API Route
    participant GitHub as GitHub API
    participant Gemini
    
    Client->>APIRoute: POST /api/generate (GitHub URL)
    APIRoute->>APIRoute: Validate & parse URL
    
    par Concurrent Fetch
        APIRoute->>GitHub: getRepoData(owner, repo)
        APIRoute->>GitHub: getRepoContents(owner, repo)
    end
    
    GitHub-->>APIRoute: Metadata (stars, description, lang)
    GitHub-->>APIRoute: Root files list
    
    APIRoute->>APIRoute: Build root files string
    APIRoute->>APIRoute: Construct README prompt
    
    APIRoute->>Gemini: Generate content with model
    Gemini-->>APIRoute: Generated markdown
    
    APIRoute->>Client: JSON response with README
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • create and add octokit #13: Provides foundational getRepoData and related Octokit utilities that this PR builds upon by adding the complementary getRepoContents function in the same module.

Suggested reviewers

  • adithyanmkd

Poem

🐰 A route springs forth with Gemini's aid,
To craft those READMEs never made,
GitHub's contents dance in the air,
With TypeScript paths resolved with care. ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The PR description uses a template with placeholder sections but does not fill in the actual summary or technical details of the changes, making it not meaningfully related to the changeset. Complete the PR description by filling in the System Summary section with actual details about the new API route, Gemini integration, and repository content fetching functionality.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'create and update the main API Route' directly relates to the main changeset, which adds a new Next.js API route at src/app/api/generate/route.ts.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch router

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@src/app/api/generate/route.ts`:
- Around line 48-51: The prompt template in route.ts interpolates
repoInfo?.language without a fallback, causing "null"/"undefined" to appear;
update the template where Primary Language is set (the block that uses Name:
${repo}, Description: ${repoInfo?.description || "A modern software project."},
Primary Language: ${repoInfo?.language}, Root Directory Files: ${fileList}) to
provide a safe default (e.g., ${repoInfo?.language || "Unknown"} or "Not
specified") so Primary Language never renders as null/undefined; keep the same
template variable names (repo, repoInfo, fileList) and only add the fallback
expression.
- Line 9: The req.json() call can throw on malformed JSON causing a 500; update
the handler to validate the request body before destructuring by reading the raw
body (e.g., await req.text()) and then JSON.parse it inside a try/catch, catch
SyntaxError and return a 400 response with a clear error message instead of
letting the outer catch produce a 500; specifically replace the line using const
{ url } = await req.json() with a safe-parse flow that assigns url only after
successful JSON.parse and handles parse failures by returning a 400 response.
- Around line 12-14: The current substring check on the incoming "url" is too
permissive; instead parse the string with the URL constructor inside the route
handler and validate the parsed hostname (e.g., allow "github.com" and
"www.github.com" only) before proceeding. In the function where "url" is read
(the route handler in src/app/api/generate/route.ts), wrap new URL(url) in a
try/catch to reject invalid URLs and then check urlObj.hostname === "github.com"
|| urlObj.hostname === "www.github.com"; if the check fails return the same
NextResponse.json({ error: "Please provide a valid GitHub URL" }, { status: 400
}). Ensure you trim the input before parsing to avoid whitespace tricks.
🧹 Nitpick comments (3)
src/lib/octokit.ts (1)

39-56: Consider adding an explicit return type to avoid any propagation.

The function returns data from repos.getContent, which has a complex union type in Octokit. Without an explicit return type, consumers (like route.ts) receive any[] and must define ad-hoc types like RepoFile. Narrowing the return type here keeps the untyped surface contained in one place.

♻️ Suggested improvement
-export async function getRepoContents(owner: string, repo: string) {
+interface RepoContentItem {
+  name: string;
+  path: string;
+  type: string;
+}
+
+export async function getRepoContents(owner: string, repo: string): Promise<RepoContentItem[]> {
   const client = getOctokit();
   
   try {
     const { data } = await client.rest.repos.getContent({
       owner,
       repo,
       path: "", // Root directory
     });
     
     // Return the array of files/folders
-    return Array.isArray(data) ? data : [];
+    return Array.isArray(data) ? data.map(({ name, path, type }) => ({ name, path, type })) : [];
   } catch (error: unknown) {
     const message = error instanceof Error ? error.message : "Could not fetch contents";
     console.error("Error fetching GitHub repo contents:", message);
     return [];
   }
 }
src/app/api/generate/route.ts (2)

35-38: Inconsistent indentation — fileList block is not indented.

Lines 35–38 break the 4-space indentation used throughout the rest of the function body. This appears to be an accidental formatting issue.

Suggested fix
-const fileList =
-  repoContents.length > 0
-    ? repoContents.map((f: RepoFile) => f.name).join(", ")
-    : "Standard repository structure";
+    const fileList =
+      repoContents.length > 0
+        ? repoContents.map((f: RepoFile) => f.name).join(", ")
+        : "Standard repository structure";

7-78: Consider adding rate limiting or request throttling for this endpoint.

This route makes calls to both the GitHub API and Gemini API on every request. Without any rate limiting, it's susceptible to abuse that could exhaust API quotas or incur unexpected costs. Consider adding middleware-level rate limiting (e.g., via next-rate-limit, Vercel's built-in rate limiting, or an upstream API gateway).

@naheel0 naheel0 merged commit 04a74ca into main Feb 9, 2026
4 checks passed
@naheel0 naheel0 deleted the router branch February 9, 2026 10:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: ai-logic Related to Gemini prompts, tokens, or model responses. area: backend Related to Next.js API routes or Octokit/GitHub API.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant