Skip to content
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

feat: add draft version support and update emoji version schema #3

Merged
merged 11 commits into from
Feb 16, 2025

Conversation

luxass
Copy link
Member

@luxass luxass commented Feb 16, 2025

Summary by CodeRabbit

  • New Features

    • Added an optional "draft" query parameter to endpoints, allowing clients to filter available versions.
    • Introduced a new endpoint for retrieving the latest draft emoji version, with appropriate error responses when no draft is available.
  • Refactor

    • Updated the latest emoji version endpoint to return a single result instead of a list.
    • Enhanced emoji version details by including a draft indicator and Unicode version information.
    • Adjusted version handling to ensure smoother request processing.
    • Streamlined the process of fetching and validating emoji data.

Copy link

coderabbitai bot commented Feb 16, 2025

Warning

Rate limit exceeded

@luxass has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 10 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.

📥 Commits

Reviewing files that changed from the base of the PR and between da73128 and 5fe5b14.

📒 Files selected for processing (4)
  • .gitignore (1 hunks)
  • src/routes/v1_categories.openapi.ts (3 hunks)
  • src/routes/v1_categories.ts (1 hunks)
  • test/routes/v1_versions.test.ts (1 hunks)

Walkthrough

This update disables the version-checking logic in the categories router and enhances the emoji version endpoints. The changes add an optional draft query parameter, update response schemas for the latest version, and introduce a new draft endpoint. Schemas have been modified to include new properties and updated types, while utility functions and type definitions have been revised to support these schema changes. Overall, the flow for fetching and validating emoji version data has been refined, and caching functionality has been removed.

Changes

File(s) Change Summary
src/routes/v1_categories.ts Disabled version validation by commenting out the getAvailableVersions call and related error handling in the middleware.
src/routes/v1_versions.openapi.ts
src/routes/v1_versions.ts
Enhanced version endpoints: added an optional draft query parameter, updated response schema (list → singular for latest version), introduced a new DRAFT_EMOJI_VERSIONS_ROUTE, and refined error handling by replacing the caching function with getAvailableVersions.
src/schemas.ts Updated EmojiVersion schema: renamed to EmojiVersionSchema, added a new boolean draft property, made emoji_version nullable, introduced a new unicode_version property, and adjusted the EMOJI_LOCK_SCHEMA to include these changes.
src/types.ts Expanded import statements and added new types EmojiLock and EmojiVersion inferred from their respective schemas.
src/utils.ts Removed the getCachedVersions function; updated getAvailableVersions to return an EmojiLock["versions"] type and to use schema validation via EMOJI_LOCK_SCHEMA.safeParse.
test/index.test.ts Updated the test URL to "https://api.mojis.dev/not-found" for 404 response testing.
test/routes/v1_versions.test.ts Introduced a new test file covering various scenarios for emoji version endpoints, including retrieving all versions, the latest version, the latest draft version, and excluding draft versions.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant CategoriesRouter
  Client->>CategoriesRouter: HTTP Request (e.g. GET /v1/categories?version=invalid)
  Note right of CategoriesRouter: Version validation removed
  CategoriesRouter-->>Client: Forwards request to next middleware
Loading
sequenceDiagram
  participant Client
  participant VersionsRouter
  participant Utils
  participant Validator
  Client->>VersionsRouter: HTTP GET /v1/draft?draft=true
  VersionsRouter->>Utils: getAvailableVersions()
  Utils->>Validator: Validate data with EmojiLock schema
  Validator-->>Utils: Returns validated emoji versions
  alt Draft version found
    Utils-->>VersionsRouter: Draft version data
    VersionsRouter-->>Client: 200 OK (Draft emoji version)
  else No draft version available
    VersionsRouter-->>Client: 404 Not Found (ApiErrorSchema)
  end
Loading

Poem

I’m a hoppin’ rabbit in a codey land so bright,
Skippin’ past validations to simplify the fight.
Draft routes and schemas bloom like springtime cheer,
No more caching tangles, everything’s now clear!
With bytes and binkies, I celebrate this day—
Carrots and code pave my joyful, rhythmic way!
🐰💻🌸


🪧 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. (Beta)
  • @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

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

🧹 Nitpick comments (5)
src/utils.ts (1)

18-34: Consider improving error messages.

The schema validation is correctly implemented, but the error messages could be more descriptive.

-    throw new Error("failed to fetch emoji data");
+    throw new Error(`Failed to fetch emoji data: ${res.status} ${res.statusText}`);

-    throw new Error("invalid emoji data schema");
+    throw new Error(`Invalid emoji data schema: ${result.error.message}`);
src/schemas.ts (1)

36-42: Consider reusing the EmojiVersion schema.

To maintain consistency and reduce duplication, consider reusing the EmojiVersion schema in the EMOJI_LOCK_SCHEMA.

-  versions: z.array(
-    z.object({
-      emoji_version: z.string().nullable(),
-      unicode_version: z.string().nullable(),
-      draft: z.boolean(),
-    }),
-  ),
+  versions: z.array(EmojiVersion.omit({
+    // Remove OpenAPI metadata as it's not needed in the lock file
+  })),
src/routes/v1_versions.ts (2)

10-18: Improve filtering logic and error handling.

Consider these improvements:

  1. The filtering logic could be more concise using optional chaining.
  2. Add specific error handling for when no versions are available.

Apply this diff to improve the code:

-    const draft = c.req.query("draft");
+    const includeDrafts = c.req.query("draft") !== "true";
 
     let versions = await getAvailableVersions();
 
-    if (draft === "true") {
-      versions = versions.filter((version) => !version.draft);
+    if (!versions?.length) {
+      return createError(c, 404, "no versions available");
     }
 
+    versions = includeDrafts ? versions : versions.filter((version) => !version.draft);
     return c.json(versions, 200);

44-56: Make the code more concise.

The filtering and error handling logic could be more concise using optional chaining and array destructuring.

Apply this diff to improve the code:

 V1_VERSIONS_ROUTER.openapi(DRAFT_EMOJI_VERSIONS_ROUTE, async (c) => {
   try {
-    const versions = (await getAvailableVersions()).filter((version) => version.draft);
-
-    if (versions[0] == null) {
+    const [draftVersion] = (await getAvailableVersions())?.filter((version) => version.draft) ?? [];
+
+    if (!draftVersion) {
       return createError(c, 404, "no draft versions available");
     }

-    return c.json(versions[0], 200);
+    return c.json(draftVersion, 200);
   } catch {
     return createError(c, 500, "failed to fetch emoji data");
   }
 });
src/routes/v1_versions.openapi.ts (1)

43-71: Extract common parameter definition.

The draft parameter definition is duplicated. Consider extracting it into a reusable constant.

Apply this diff to improve the code:

+const DRAFT_PARAMETER = {
+  in: "query",
+  name: "draft",
+  required: false,
+  description: "Whether to include draft versions",
+  schema: {
+    type: "string",
+    enum: ["true", "false"],
+  },
+} as const;

 export const ALL_EMOJI_VERSIONS_ROUTE = createRoute({
   // ...
-  parameters: [
-    {
-      in: "query",
-      name: "draft",
-      required: false,
-      description: "Whether to include draft versions",
-      schema: {
-        type: "boolean",
-      },
-    },
-  ],
+  parameters: [DRAFT_PARAMETER],
   // ...
 });

 export const LATEST_EMOJI_VERSIONS_ROUTE = createRoute({
   // ...
-  parameters: [
-    {
-      in: "query",
-      name: "draft",
-      required: false,
-      description: "Whether to include draft versions",
-      schema: {
-        type: "boolean",
-      },
-    },
-  ],
+  parameters: [DRAFT_PARAMETER],
   // ...
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c837d9a and 7d62c8d.

📒 Files selected for processing (6)
  • src/routes/v1_categories.ts (2 hunks)
  • src/routes/v1_versions.openapi.ts (2 hunks)
  • src/routes/v1_versions.ts (1 hunks)
  • src/schemas.ts (2 hunks)
  • src/types.ts (2 hunks)
  • src/utils.ts (3 hunks)
🔇 Additional comments (7)
src/types.ts (2)

2-2: LGTM!

The import statement is correctly structured and aligns with the new type definition.


14-14: LGTM!

The EmojiLock type is correctly defined and aligns with the schema changes.

src/routes/v1_categories.ts (2)

3-3: LGTM!

The import statement is correctly updated to remove unused imports.


15-19:

❓ Verification inconclusive

Verify the implications of disabling version validation.

While commenting out the version validation aligns with the PR objectives to support draft versions, please ensure that:

  1. This is not a temporary change (commented code should be removed if permanent).
  2. The removal of version validation doesn't lead to unintended acceptance of invalid versions.

Run this script to check for version validation in other routes:


🏁 Script executed:

#!/bin/bash
# Description: Check if version validation is handled elsewhere
# Look for version validation patterns in route files
rg -A 5 'version.*param|param.*version' src/routes/

Length of output: 599


Confirm the impact of disabling version validation

Based on our verification, the version validation logic in src/routes/v1_categories.ts has been commented out without any alternative check elsewhere. The code still rejects requests missing a version parameter, but it no longer verifies whether the provided version (e.g., "latest" or any other value) is valid.

Please ensure that:

  • If this change is intended for draft version support, remove the commented-out code to avoid confusion.
  • The absence of the additional version validation does not open up the possibility of processing unintended or invalid version values.
  • If this is a temporary measure, add a clear TODO or FIXME comment to revisit the validation logic before the final release.
src/utils.ts (1)

3-4: LGTM!

The import statements are correctly updated to support the new schema validation.

src/schemas.ts (1)

4-16: LGTM!

The schema updates are well-structured with:

  • Clear descriptions and examples for each property
  • Correct nullable types for version fields
  • Proper OpenAPI documentation
src/routes/v1_versions.openapi.ts (1)

74-104: LGTM!

The route definition is well-structured with appropriate response schemas and error handling.

Comment on lines +25 to 41
try {
const draft = c.req.query("draft");

let versions = await getAvailableVersions();

if (draft === "true") {
versions = versions.filter((version) => !version.draft);
}

if (versions[0] == null) {
return createError(c, 500, "failed to fetch emoji data");
}

if (!res.ok) {
return c.json(versions[0], 200);
} catch {
return createError(c, 500, "failed to fetch emoji data");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reduce code duplication and improve consistency.

The draft parameter handling is duplicated from ALL_EMOJI_VERSIONS_ROUTE. Consider extracting the common logic into a utility function.

Apply this diff to improve the code:

+async function getFilteredVersions(draft: string | null) {
+  const includeDrafts = draft !== "true";
+  const versions = await getAvailableVersions();
+  return includeDrafts ? versions : versions.filter((version) => !version.draft);
+}

 V1_VERSIONS_ROUTER.openapi(LATEST_EMOJI_VERSIONS_ROUTE, async (c) => {
   try {
-    const draft = c.req.query("draft");
-
-    let versions = await getAvailableVersions();
-
-    if (draft === "true") {
-      versions = versions.filter((version) => !version.draft);
-    }
+    const versions = await getFilteredVersions(c.req.query("draft"));

     if (versions[0] == null) {
       return createError(c, 500, "failed to fetch emoji data");
     }

     return c.json(versions[0], 200);
   } catch {
     return createError(c, 500, "failed to fetch emoji data");
   }
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const draft = c.req.query("draft");
let versions = await getAvailableVersions();
if (draft === "true") {
versions = versions.filter((version) => !version.draft);
}
if (versions[0] == null) {
return createError(c, 500, "failed to fetch emoji data");
}
if (!res.ok) {
return c.json(versions[0], 200);
} catch {
return createError(c, 500, "failed to fetch emoji data");
}
async function getFilteredVersions(draft: string | null) {
const includeDrafts = draft !== "true";
const versions = await getAvailableVersions();
return includeDrafts ? versions : versions.filter((version) => !version.draft);
}
V1_VERSIONS_ROUTER.openapi(LATEST_EMOJI_VERSIONS_ROUTE, async (c) => {
try {
const versions = await getFilteredVersions(c.req.query("draft"));
if (versions[0] == null) {
return createError(c, 500, "failed to fetch emoji data");
}
return c.json(versions[0], 200);
} catch {
return createError(c, 500, "failed to fetch emoji data");
}
});

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

🧹 Nitpick comments (1)
test/routes/v1_versions.test.ts (1)

42-55: Add negative test case for draft versions.

Consider adding a test case for when no draft versions are available to verify the 404 response.

it("should return 404 when no draft versions are available", async () => {
  const request = new Request("https://api.mojis.dev/api/v1/versions/draft");
  const ctx = createExecutionContext();
  const response = await worker.fetch(request, env, ctx);
  await waitOnExecutionContext(ctx);

  expect(response.status).toBe(404);
  const data = await response.json();
  expect(data).toMatchObject({
    message: expect.any(String),
    status: 404,
    path: "/api/v1/versions/draft",
    timestamp: expect.any(String),
  });
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d62c8d and da73128.

📒 Files selected for processing (5)
  • src/routes/v1_versions.openapi.ts (2 hunks)
  • src/schemas.ts (2 hunks)
  • src/types.ts (2 hunks)
  • test/index.test.ts (1 hunks)
  • test/routes/v1_versions.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/types.ts
🔇 Additional comments (8)
test/index.test.ts (1)

10-10: LGTM!

The URL update correctly reflects the new API domain while maintaining the test's purpose of verifying 404 responses.

src/schemas.ts (2)

3-16: LGTM! Schema changes are well-structured and documented.

The schema updates appropriately support draft versions with:

  • Clear property descriptions and examples
  • Nullable version fields for draft versions
  • Consistent OpenAPI documentation

35-43: LGTM! Lock schema updated consistently.

The EMOJI_LOCK_SCHEMA has been correctly updated to match the new version structure.

src/routes/v1_versions.openapi.ts (4)

4-13: LGTM! Draft parameter is well-defined.

The parameter definition follows the suggested string enum approach for better type safety.


19-21: LGTM! Route updated consistently.

The all versions route correctly:

  • Includes the draft parameter
  • Uses the updated schema

Also applies to: 26-26


46-48: LGTM! Latest version route updated consistently.

The latest version route correctly:

  • Includes the draft parameter
  • Uses the updated schema
  • Has an accurate description

Also applies to: 53-53, 56-57


69-99: LGTM! Draft versions route is well-defined.

The new route includes:

  • Appropriate path and method
  • Clear description
  • Proper error responses (404 for no drafts)
  • Consistent error handling
test/routes/v1_versions.test.ts (1)

12-12: Ensure consistent API URLs across tests.

The base URL "https://mojis.dev" differs from "https://api.mojis.dev" used in index.test.ts.

Update the URLs to maintain consistency:

-    const request = new Request("https://mojis.dev/api/v1/versions");
+    const request = new Request("https://api.mojis.dev/api/v1/versions");

And similarly for other test cases.

Also applies to: 28-28, 43-43, 58-58

@luxass luxass merged commit 96fd77a into main Feb 16, 2025
2 checks passed
@luxass luxass deleted the versions-endpoints branch February 16, 2025 10:41
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