Skip to content

Add endpoint for fetching a post, Update docs #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 19, 2025
Merged

Add endpoint for fetching a post, Update docs #70

merged 2 commits into from
May 19, 2025

Conversation

arjunkomath
Copy link
Member

@arjunkomath arjunkomath commented May 19, 2025

Summary by CodeRabbit

  • New Features

    • Added a new API endpoint to fetch a single post by its ID.
    • Introduced a new URL pattern for accessing individual posts via /changes.json/:id.
  • Documentation

    • Updated documentation to include details about the new endpoint for fetching posts by ID and improved heading consistency.
  • Bug Fixes

    • Improved error messages for API endpoints to provide clearer information when issues occur.

Copy link

vercel bot commented May 19, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
changes-page-docs ✅ Ready (Inspect) Visit Preview May 19, 2025 0:45am
user-changes-page ✅ Ready (Inspect) Visit Preview May 19, 2025 0:45am
1 Skipped Deployment
Name Status Preview Updated (UTC)
changes-page ⬜️ Skipped (Inspect) May 19, 2025 0:45am

Copy link

coderabbitai bot commented May 19, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A new API endpoint was added to fetch a single post by ID, including both backend implementation and documentation. Next.js rewrite rules were updated to route requests to the new endpoint. Several API handlers had their error logging messages improved for clarity. No changes were made to existing public interfaces or exported entities except for the new endpoint.

Changes

File(s) Change Summary
apps/docs/content/docs/api/page.mdx Updated documentation: corrected heading and added section for new "Get latest post by ID" endpoint.
apps/page/next.config.js Added rewrite rule mapping /changes.json/:id to /api/post/:id.
apps/page/pages/api/post/[id].ts Introduced new API handler to fetch a single post by ID, including CORS and Supabase integration.
apps/page/pages/api/json.ts
apps/page/pages/api/latest.ts
apps/page/pages/api/markdown.ts
apps/page/pages/api/pinned.ts
Improved error logging messages for clarity and specificity.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Next.js Router
    participant API Handler ([id].ts)
    participant Supabase
    participant Docs

    Client->>Next.js Router: GET /changes.json/:id
    Next.js Router->>API Handler ([id].ts): /api/post/:id
    API Handler ([id].ts)->>Supabase: Query post by ID and page
    Supabase-->>API Handler ([id].ts): Post data
    API Handler ([id].ts)-->>Client: JSON response with post (or 404)
    Docs-->>Client: Documents new endpoint usage
Loading

Poem

In the warren of code, a new path appears,
Fetching posts by ID—let’s give three cheers!
With clearer logs and routes anew,
The docs now tell you what to do.
🐇 Hopping forward, APIs refined,
One more carrot for peace of mind!


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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

@arjunkomath
Copy link
Member Author

@coderabbitai review

Copy link

coderabbitai bot commented May 19, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (5)
apps/docs/content/docs/api/page.mdx (1)

74-74: Fix grammar in heading

The singular article "a" doesn't match with the plural noun "posts".

-### Get a posts by id
+### Get a post by id
🧰 Tools
🪛 LanguageTool

[grammar] ~74-~74: It looks like ‘posts’ doesn’t match ‘a’. Did you mean “a post” or just “posts”?
Context: ...requested features!" } ] ``` ### Get a posts by id This endpoint will return a JSON...

(A_NNS_IN)

apps/page/pages/api/post/[id].ts (4)

62-68: Consider simplifying single post URL mapping

Since you're only working with a single post (as indicated by the limit(1)), you could simplify this mapping operation.

-    const postsWithUrl = posts.map((post) => {
-      return {
-        ...post,
-        url: getPostUrl(pageUrl, post),
-      };
-    });
-
-    res.status(200).json(postsWithUrl[0] ?? null);
+    const post = posts[0];
+    res.status(200).json({
+      ...post,
+      url: getPostUrl(pageUrl, post),
+    });

70-70: Fix error type annotation in catch clause

The catch clause variable type annotation must be 'any' or 'unknown' if specified.

-  } catch (e: Error | any) {
+  } catch (e: unknown) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 70-70: Catch clause variable type annotation must be 'any' or 'unknown' if specified.

(parse)


71-71: Enhance error logging

Consider improving the error logging to include more context about the error.

-    console.log("Failed to fetch post [Error]", e);
+    console.error("Failed to fetch post by ID:", id, e instanceof Error ? e.message : e);

20-24: Validate ID format before processing

Consider validating that the ID is in the expected UUID format before proceeding with the database query.

   const { id } = req.query;
-  if (!id) {
+  // Validate ID is present and in the expected format
+  const postId = String(id);
+  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+  
+  if (!postId || !uuidRegex.test(postId)) {
     res.status(404).json(null);
     return;
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 2b63829 and fdeb4d9.

📒 Files selected for processing (7)
  • apps/docs/content/docs/api/page.mdx (2 hunks)
  • apps/page/next.config.js (1 hunks)
  • apps/page/pages/api/json.ts (2 hunks)
  • apps/page/pages/api/latest.ts (1 hunks)
  • apps/page/pages/api/markdown.ts (1 hunks)
  • apps/page/pages/api/pinned.ts (1 hunks)
  • apps/page/pages/api/post/[id].ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/page/pages/api/post/[id].ts (3)
packages/supabase/types/page.ts (1)
  • IPost (6-6)
apps/page/lib/data.ts (2)
  • translateHostToPageIdentifier (360-360)
  • fetchRenderData (357-357)
packages/supabase/admin.ts (1)
  • supabaseAdmin (4-7)
🪛 LanguageTool
apps/docs/content/docs/api/page.mdx

[grammar] ~74-~74: It looks like ‘posts’ doesn’t match ‘a’. Did you mean “a post” or just “posts”?
Context: ...requested features!" } ] ``` ### Get a posts by id This endpoint will return a JSON...

(A_NNS_IN)

🪛 Biome (1.9.4)
apps/page/pages/api/post/[id].ts

[error] 70-70: Catch clause variable type annotation must be 'any' or 'unknown' if specified.

(parse)

🔇 Additional comments (10)
apps/page/pages/api/latest.ts (1)

62-62: Improved error logging for better debugging

The error message is now more specific, which will improve debugging and error tracking capabilities.

apps/page/pages/api/pinned.ts (1)

63-63: Enhanced error message for clarity

The error logging message is now more descriptive, clearly indicating that the failure occurred while fetching a pinned post.

apps/page/pages/api/markdown.ts (1)

43-43: More detailed error logging

The improved error message now provides context about both the operation that failed and the endpoint, which will help with debugging.

apps/page/pages/api/json.ts (2)

2-3: Import reordering looks good

The import statements have been reordered to place utility imports before framework imports, which improves organization.


46-46: Enhanced error logging message

Improved error message clarity is consistent with the pattern applied to other API handlers in this PR.

apps/page/next.config.js (1)

90-93: Well-implemented rewrite rule for new post endpoint

The new rewrite rule correctly maps /changes.json/:id to the new /api/post/:id endpoint, following the established pattern of other API routes in the application.

This change properly exposes the new API functionality for fetching individual posts by ID, which aligns with the PR objective of adding a new endpoint for fetching a post.

apps/docs/content/docs/api/page.mdx (1)

75-93: Documentation for new endpoint looks good

The documentation follows the established pattern for API endpoints in this file, with clear request format and example response structure.

apps/page/pages/api/post/[id].ts (3)

1-10: Imports look good

All necessary imports are properly structured and organized.


11-15: IPostWithUrl type definition is appropriate

The type definition properly extends the IPost type with a URL field.


41-49: Query parameters and constraints look good

The Supabase query properly filters for the specified post ID, page ID, and published status.

Comment on lines +55 to +60
const posts = data as Array<IPost>;

if (!posts?.length) {
res.status(404).json(null);
return;
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Add plain_text_content to response

Based on the example response in the documentation, the API should include a plain_text_content field, but it's not selected in the query or added to the response.


🏁 Script executed:

#!/bin/bash
# Check if the IPost type includes plain_text_content field
rg -A 15 "export type IPost" packages/supabase/types/page.ts

# Check if other post endpoints include plain_text_content
rg -A 5 "plain_text_content" apps/page/pages/api

Length of output: 1050


Include plain_text_content in the post detail response

The GET /api/post/[id] handler currently returns the raw IPost rows, but the example response in our docs and the /api/json endpoint both include a computed plain_text_content field. Since IPost is just a direct mapping of your DB row, you need to append this field yourself.

• File: apps/page/pages/api/post/[id].ts
After you’ve fetched and validated posts (around where you call res.status(200).json(...)), map each post to include the plain‐text content:

import { convertMarkdownToPlainText } from 'path/to/markdown-utils';

const postsWithPlainText = posts.map(post => ({
  ...post,
  plain_text_content: convertMarkdownToPlainText(post.content),
}));

res.status(200).json(postsWithPlainText);

This will keep your detail endpoint consistent with the docs and the JSON list endpoint.

🤖 Prompt for AI Agents
In apps/page/pages/api/post/[id].ts around lines 55 to 60, the API response
currently returns posts without the plain_text_content field required by the
documentation. To fix this, after validating the posts array, map each post to
add a plain_text_content property by converting the post's content from markdown
to plain text using a utility function like convertMarkdownToPlainText. Then
return this mapped array in the JSON response to ensure the API output matches
the documented format.

@vercel vercel bot temporarily deployed to Preview – changes-page May 19, 2025 12:43 Inactive
@arjunkomath arjunkomath merged commit 9c66f23 into main May 19, 2025
6 checks passed
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