Skip to content

feat(gateway): add github emojis route and version middleware#8

Merged
luxass merged 2 commits intomainfrom
gateway
Mar 1, 2025
Merged

feat(gateway): add github emojis route and version middleware#8
luxass merged 2 commits intomainfrom
gateway

Conversation

@luxass
Copy link
Copy Markdown
Member

@luxass luxass commented Feb 28, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new gateway API endpoint for GitHub integrations, including a route to retrieve GitHub emojis.
    • Enhanced API documentation with an additional category for gateway-related endpoints.
    • Improved version handling for API requests, ensuring clear error responses and proper redirection when needed.
  • Chores

    • Updated repository configuration to ignore local development variables.
    • Implemented an enhanced caching mechanism to optimize response delivery.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 28, 2025

Walkthrough

The changes introduce several new functionalities and improvements. A new entry, .dev.vars, is added to the .gitignore file to exclude specific files from Git tracking. A new GitHub emoji endpoint is integrated into the routing with corresponding OpenAPI documentation. A versionMiddleware is introduced to validate and manage request versions, replacing a previous custom middleware in one endpoint. Additionally, a new router for GitHub endpoints is created, a caching utility function is implemented, and a GITHUB_TOKEN property is added to the types for authorization.

Changes

File(s) Change Summary
.gitignore Added entry .dev.vars to ignore development variable files.
src/index.ts Integrated GATEWAY_GITHUB_ROUTER into the routing configuration; added a new "Gateway" OpenAPI tag with description; removed .tag-section CSS styling.
src/middlewares/version.ts Introduced a new versionMiddleware that validates the version parameter, fetches available versions, handles redirection for "latest", and manages error responses.
src/routes/gateway_github.openapi.ts, src/routes/gateway_github.ts Added a new GitHub emoji endpoint: The OpenAPI route (/emojis) documents responses while the router fetches and caches GitHub emoji data.
src/routes/v1_categories.ts Replaced the custom version validation middleware with the new versionMiddleware and removed the unused import for getAvailableVersions.
src/types.ts Updated the Bindings interface by adding the required property GITHUB_TOKEN of type string.
src/utils.ts Added a new cache function that sets appropriate HTTP caching headers based on the provided age and immutability flag.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant VM as versionMiddleware
    participant AV as AvailableVersions
    participant R as Route Handler

    C->>VM: Send request with version parameter
    alt Version missing
       VM-->>C: 400 Error ("missing version")
    else "latest" version provided
       VM->>AV: Fetch available versions
       alt No valid version found
          VM-->>C: 404 Error ("no versions available")
       else Valid version found
          VM->>R: Update request path and forward request
          R-->>C: Processed response (200 OK)
       end
    end
Loading
sequenceDiagram
    participant C as Client
    participant GR as GitHub Router
    participant API as GitHub API
    participant Cache as Cache Utility

    C->>GR: GET /api/gateway/github/emojis
    GR->>API: Request GitHub Emoji Data (with headers)
    alt API returns error
       API-->>GR: Error response
       GR-->>C: 500 Internal Server Error
    else API returns emoji data
       API-->>GR: JSON Emoji Data
       GR->>Cache: Cache response for 1 hour
       GR-->>C: 200 OK with emoji data
    end
Loading

Poem

I'm a hopping rabbit, swift and keen,
Bounding through code with a shiny new scene.
Routes for emojis and versions to steer,
Caches that sparkle, the future is here!
With tokens and tags in a digital land,
I celebrate these changes with a twitch of my hand!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78c1f08 and f3bfeab.

📒 Files selected for processing (2)
  • src/middlewares/version.ts (1 hunks)
  • src/routes/gateway_github.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/middlewares/version.ts
  • src/routes/gateway_github.ts

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

Copy link
Copy Markdown

@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: 0

🧹 Nitpick comments (2)
src/routes/gateway_github.ts (1)

8-21: Consider adding error handling refinements and rate limiting awareness.

The implementation correctly uses the GitHub API with proper headers and authentication. However, there are a few refinements that could be made:

  1. The error handling is generic - consider capturing specific error details from GitHub's response
  2. GitHub API has rate limits - consider implementing retry logic or checking rate limit headers
 GATEWAY_GITHUB_ROUTER.openapi(GITHUB_EMOJIS_ROUTE, async (c) => {
   const response = await fetch("https://api.github.com/emojis", {
     headers: {
       "Accept": "application/vnd.github.v3+json",
       "X-GitHub-Api-Version": "2022-11-28",
       "Authorization": `Bearer ${c.env.GITHUB_TOKEN}`,
       "User-Agent": "luxass - (api.mojis.dev)",
     },
   });
 
   if (!response.ok) {
-    return createError(c, 500, "Internal Server Error");
+    const errorData = await response.text();
+    console.error(`GitHub API error: ${response.status} - ${errorData}`);
+    return createError(c, 500, "Failed to fetch GitHub emojis");
   }
src/middlewares/version.ts (1)

26-26: Consider replacing hardcoded fallback value "15.1"

The fallback value "15.1" appears to be hardcoded. Consider moving this to a constant or configuration value to improve maintainability.

- const path = fullPath.replace("latest", latestVersion.emoji_version ?? "15.1");
+ const DEFAULT_VERSION = "15.1";
+ const path = fullPath.replace("latest", latestVersion.emoji_version ?? DEFAULT_VERSION);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between efc5f78 and 78c1f08.

📒 Files selected for processing (8)
  • .gitignore (1 hunks)
  • src/index.ts (3 hunks)
  • src/middlewares/version.ts (1 hunks)
  • src/routes/gateway_github.openapi.ts (1 hunks)
  • src/routes/gateway_github.ts (1 hunks)
  • src/routes/v1_categories.ts (1 hunks)
  • src/types.ts (1 hunks)
  • src/utils.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🔇 Additional comments (11)
src/types.ts (1)

8-8: LGTM! Addition of GITHUB_TOKEN is required for the new GitHub emojis route.

The new field properly extends the Bindings interface to provide the GitHub token needed for authentication with the GitHub API. This is consistent with the new functionality added in the gateway_github.ts file.

src/routes/gateway_github.openapi.ts (1)

1-28: LGTM! Well-structured OpenAPI route definition for GitHub emojis.

The OpenAPI configuration for the new GitHub emojis endpoint is properly defined with appropriate:

  • HTTP method (GET)
  • Path (/emojis)
  • Tags for API documentation categorization
  • Response schemas for both success (200) and error (500) cases

The schema using z.record(z.string()) correctly represents the expected response format from GitHub's emoji API.

src/utils.ts (1)

36-46: LGTM! Well-implemented cache utility function with appropriate options.

The cache function is well designed with:

  • Support for both cache prevention (-1 age) and enablement
  • Proper HTTP cache headers (Expires, Pragma, Cache-Control)
  • Optional immutable flag for cache optimization
  • Clean implementation using conditional logic

This will help optimize performance for the GitHub emojis endpoint.

src/routes/gateway_github.ts (2)

1-7: LGTM! Good router setup with proper imports and base path.

The GitHub gateway router is properly set up with the correct base path and imports.


22-27: LGTM! Good use of caching with appropriate cache duration.

The implementation correctly:

  1. Parses the JSON response from GitHub
  2. Applies caching with a reasonable duration (1 hour)
  3. Sets the cache as immutable (appropriate since GitHub emojis rarely change)
  4. Returns the data with the correct status code
src/middlewares/version.ts (1)

4-32: Well-implemented version middleware with complete validation flow

The middleware effectively handles all necessary validation cases for version parameters, including missing versions, invalid versions, and the special "latest" case. The flow is logical and provides appropriate error responses.

src/index.ts (3)

8-8: Good addition of GitHub router import

The import is correctly structured and follows the existing pattern in the file.


16-16: GitHub router properly integrated into application routing

The router is correctly added to the application's routing configuration with the same pattern as other routers.


86-89: Well-documented OpenAPI tag for Gateway endpoints

The new Gateway tag is properly structured and provides clear description for API documentation.

src/routes/v1_categories.ts (2)

3-5: Proper imports for middleware implementation

The import changes correctly reflect the transition to using the centralized version middleware, removing the now unnecessary getAvailableVersions import.


10-10: Good refactoring to use centralized version middleware

Replacing the custom middleware with the centralized versionMiddleware improves code maintainability and reduces duplication.

…and improve error logging in GitHub API route
@luxass luxass merged commit 6d772d2 into main Mar 1, 2025
@luxass luxass deleted the gateway branch March 1, 2025 05:06
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