8000 chore: use same schema for prefix and bytes by ogzhanolguncu · Pull Request #3284 · unkeyed/unkey · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

chore: use same schema for prefix and bytes #3284

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 3 commits into from
May 29, 2025
Merged

chore: use same schema for prefix and bytes #3284

merged 3 commits into from
May 29, 2025

Conversation

ogzhanolguncu
Copy link
Contributor
@ogzhanolguncu ogzhanolguncu commented May 29, 2025

What does this PR do?

Improves error handling and makes it more user friendly for bytes and prefix API settings updates. And, uses SSOT for schemas.

Fixes # (issue)

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Test A
  • Test B

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features
    • Improved success and error messages for updating default bytes and prefix, providing more detailed feedback and support options for users.
  • Bug Fixes
    • Enhanced error handling for default bytes and prefix updates, offering clearer guidance for specific error cases.
  • Refactor
    • Updated validation for default bytes and prefix fields to use centralized, reusable schemas for greater consistency.
    • Restructured backend error handling to centralize and standardize error management during updates.

Copy link
linear bot commented May 29, 2025

Copy link
changeset-bot bot commented May 29, 2025

⚠️ No Changeset found

Latest commit: 724d7e9

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
vercel bot commented May 29, 2025

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

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 29, 2025 3:32pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
engineering ⬜️ Ignored (Inspect) Visit Preview May 29, 2025 3:32pm

Copy link
Contributor
coderabbitai bot commented May 29, 2025
📝 Walkthrough

"""

Walkthrough

Validation schemas for default bytes and default prefix settings were refactored to use centralized, reusable schemas. Error handling in both the frontend components and backend procedures was enhanced, providing more specific user feedback and centralizing error management logic. No changes were made to public entity signatures.

Changes

File(s) Change Summary
apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-bytes.tsx Switched to reusable validation schema, improved success toasts, and expanded detailed error handling.
apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-prefix.tsx Switched to reusable validation schema, improved success toasts, and expanded detailed error handling.
apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts Switched to reusable validation schema and centralized error handling using try-catch.
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts Switched to reusable validation schema for prefix; no other logic or error handling changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI_Component as DefaultBytes/DefaultPrefix Component
    participant API as TRPC API Procedure
    participant DB as Database

    User->>UI_Component: Submit new defaultBytes/defaultPrefix
    UI_Component->>UI_Component: Validate input with reusable schema
    UI_Component->>API: Send mutation request
    API->>API: Validate input with reusable schema
    API->>DB: Update keyAuth record
    alt Success
        API-->>UI_Component: Return success
        UI_Component-->>User: Show success toast with details
    else Error (NOT_FOUND/INTERNAL_SERVER_ERROR/BAD_REQUEST)
        API-->>UI_Component: Return error with code
        UI_Component-->>User: Show specific error toast
    else Other Error
        API-->>UI_Component: Return generic error
        UI_Component-->>User: Show fallback error toast with support link
    end
Loading

Possibly related PRs

Suggested reviewers

  • mcstepp
  • perkinsjr
  • chronark
    """

📜 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 a5fc57b and 724d7e9.

📒 Files selected for processing (2)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-bytes.tsx (2 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-prefix.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-bytes.tsx
  • apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-prefix.tsx
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

Copy link
Contributor
github-actions bot commented May 29, 2025

Thank you for following the naming conventions for pull request titles! 🙏

Copy link
Contributor
@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

🔭 Outside diff range comments (1)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)

18-84: 🛠️ Refactor suggestion

Inconsistent error handling pattern with setDefaultBytes.ts.

This procedure still uses the old .catch() pattern for error handling, while setDefaultBytes.ts has been refactored to use a cleaner try-catch approach. Consider updating this for consistency.

Apply this refactor to match the pattern in setDefaultBytes.ts:

  .mutation(async ({ ctx, input }) => {
-    const keyAuth = await db.query.keyAuth
-      .findFirst({
-        where: (table, { eq, and, isNull }) =>
-          and(
-            eq(table.workspaceId, ctx.workspace.id),
-            eq(table.id, input.keyAuthId),
-            isNull(table.deletedAtM),
-          ),
-      })
-      .catch((_err) => {
-        throw new TRPCError({
-          code: "INTERNAL_SERVER_ERROR",
-          message:
-            "We were unable to update the key auth. Please try again or contact support@unkey.dev",
-        });
-      });
+    const keyAuth = await db.query.keyAuth.findFirst({
+      where: (table, { eq, and, isNull }) =>
+        and(
+          eq(table.workspaceId, ctx.workspace.id),
+          eq(table.id, input.keyAuthId),
+          isNull(table.deletedAtM),
+        ),
+    });
+
     if (!keyAuth) {
       throw new TRPCError({
         code: "NOT_FOUND",
         message:
           "We are unable to find the correct key auth. Please try again or contact support@unkey.dev.",
       });
     }

-    await db
-      .transaction(async (tx) => {
+    try {
+      await db.transaction(async (tx) => {
         await tx
           .update(schema.keyAuth)
           .set({
             defaultPrefix: input.defaultPrefix,
           })
-          .where(eq(schema.keyAuth.id, keyAuth.id))
-          .catch((_err) => {
-            throw new TRPCError({
-              code: "INTERNAL_SERVER_ERROR",
-              message:
-                "We were unable to update the API default prefix. Please try again or contact support@unkey.dev.",
-            });
-          });
+          .where(eq(schema.keyAuth.id, keyAuth.id));
+
         await insertAuditLogs(tx, {
           workspaceId: ctx.workspace.id,
           actor: {
             type: "user",
             id: ctx.user.id,
           },
           event: "api.update",
           description: `Changed ${keyAuth.id} default prefix from ${keyAuth.defaultPrefix} to ${input.defaultPrefix}`,
           resources: [
             {
               type: "keyAuth",
               id: keyAuth.id,
             },
           ],
           context: {
             location: ctx.audit.location,
             userAgent: ctx.audit.userAgent,
           },
         });
-      })
-      .catch((_err) => {
+      });
+    } catch (err) {
+      console.error(err);
       throw new TRPCError({
         code: "INTERNAL_SERVER_ERROR",
         message:
           "We were unable to update the default prefix. Please try again or contact support@unkey.dev.",
       });
-      });
+    }
   });
🧹 Nitpick comments (1)
apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-prefix.tsx (1)

51-69: Consider adding BAD_REQUEST error handling for consistency.

The error handling is good, but it's missing the BAD_REQUEST case that's handled in the default-bytes.tsx component. Consider adding it for consistency.

Add this error case between the INTERNAL_SERVER_ERROR and fallback cases:

      } else if (err.data?.code === "INTERNAL_SERVER_ERROR") {
        toast.error("Server Error", {
          description:
            "We encountered an issue while updating the default prefix. Please try again later or contact support at support@unkey.dev",
        });
+      } else if (err.data?.code === "BAD_REQUEST") {
+        toast.error("Invalid Configuration", {
+          description: `Please check your prefix settings. ${err.message || ""}`,
+        });
      } else {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 146fabe and b40727f.

📒 Files selected for processing (4)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-bytes.tsx (2 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-prefix.tsx (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)
apps/dashboard/app/(app)/apis/[apiId]/_components/create-key/create-key.schema.ts (1)
  • keyPrefixSchema (27-37)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (13)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2)

4-4: LGTM: Schema centralization improves maintainability.

Good move to import the centralized keyPrefixSchema to maintain consistency across the application.


14-14:

❌ Incorrect review comment

Verify the .pipe(z.string()) transformation.

The keyPrefixSchema is defined as optional (.optional() in the schema), but piping it to z.string() makes it required. Please confirm this is the intended behavior, as it changes the validation contract.


🏁 Script executed:

#!/bin/bash
# Description: Verify how keyPrefixSchema is used across the codebase to ensure consistency

# Search for other usages of keyPrefixSchema to check if .pipe(z.string()) is used consistently
rg -A 2 -B 2 "keyPrefixSchema" --type ts

Length of output: 3538


Ignore the optionalness concern.

The keyPrefixSchema is defined as a required z.string().max(8) (no .optional()), so .pipe(z.string()) does not alter its requiredness or change the validation contract. This usage is consistent in:

  • create-key.schema.ts (defines keyPrefixSchema)
  • default-prefix.tsx (client-side form schema)
  • setDefaultPrefix.ts (TRPC input schema)

No changes are needed.

Likely an incorrect or invalid review comment.

apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-bytes.tsx (4)

11-11: LGTM: Schema centralization implemented correctly.

Good use of the centralized keyBytesSchema to maintain consistency across the application.


15-15: LGTM: Clean schema usage.

The direct usage of keyBytesSchema is correct and simpler than the prefix component's .pipe(z.string()) approach.


43-45: LGTM: Enhanced user feedback.

The success toast now provides clear, descriptive feedback with both title and description, improving the user experience.


51-73: Excellent error handling implementation.

The comprehensive error handling with specific error codes provides much better user feedback compared to generic error messages. The contact support action is a nice touch for unhandled errors.

apps/dashboard/app/(app)/apis/[apiId]/settings/components/default-prefix.tsx (3)

11-11: LGTM: Consistent schema centralization.

Good implementation of the centralized keyPrefixSchema import.


15-15: Consistent with backend implementation.

The .pipe(z.string()) usage matches the backend procedure, maintaining consistency between frontend and backend validation.


43-45: LGTM: Improved success feedback.

The enhanced success toast provides clear, descriptive feedback improving user experience.

apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (4)

1-1: LGTM: Schema centralization implemented.

Good use of the centralized keyBytesSchema for consistent validation.


13-13: LGTM: Clean schema usage.

Direct usage of keyBytesSchema is straightforward and maintains consistency.


18-25: LGTM: Simplified database query.

Removing the .catch block allows errors to propagate naturally to the outer error handling, which is cleaner.


35-71: Excellent error handling refactor.

The refactored error handling with explicit try-catch is much cleaner than the previous nested .catch() approach. The error logging will help with debugging, and the centralized error message provides consistent user feedback.

@ogzhanolguncu ogzhanolguncu added this pull request to the merge queue May 29, 2025
Merged via the queue into main with commit 62d5d61 May 29, 2025
30 checks passed
@ogzhanolguncu ogzhanolguncu deleted the ENG-1800 branch May 29, 2025 19:32
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.

2 participants
0