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

fix imports #58

Merged
merged 4 commits into from
Nov 21, 2024
Merged

fix imports #58

merged 4 commits into from
Nov 21, 2024

Conversation

wtfdivyansh
Copy link
Contributor

@wtfdivyansh wtfdivyansh commented Nov 21, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced email sending functionality with dynamic imports for improved performance.
    • Added standardized error messaging for email operations.
  • Bug Fixes

    • Updated the route for the /test endpoint, ensuring correct functionality after variable renaming.
  • Refactor

    • Changed handler from asynchronous to synchronous for the health check endpoint, optimizing control flow.
    • Streamlined route definitions in various endpoints for improved readability and maintainability.

Copy link

vercel bot commented Nov 21, 2024

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

Name Status Preview Comments Updated (UTC)
plura-api ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 21, 2024 3:46pm
plura-status ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 21, 2024 3:46pm

Copy link

coderabbitai bot commented Nov 21, 2024

Walkthrough

This pull request includes modifications across several files within the API. The handler for the GET request at the root path of the health endpoint is changed from asynchronous to synchronous. The email sending functionality is updated to use dynamic imports for the sendEmail and sendBatchEmail functions, while maintaining existing response structures. Additionally, the route for the /test endpoint is renamed to reflect a change in the variable name used for the route definition. Other files also see structural improvements, such as combining instance creation with route definitions.

Changes

File Path Change Summary
apps/api/app/api/[[...route]]/health.ts Changed handler from asynchronous to synchronous for GET request at "/" path.
apps/api/app/api/[[...route]]/mail.ts Updated to dynamic imports for sendEmail and sendBatchEmail. Maintained response structure.
apps/api/app/api/[[...route]]/route.ts Renamed route from /test to /hello, updating variable name used in route definition.
apps/api/app/api/[[...route]]/auth.ts Combined Hono instance creation and event handler definition into a single line.
apps/api/app/api/[[...route]]/session.ts Restructured route definitions for "/" and "/all" paths, integrating session checks directly.
apps/api/app/api/[[...route]]/status.ts Refactored route definitions to use method chaining for improved readability.
apps/api/app/api/[[...route]]/test.ts Combined Hono instance creation with GET route definition into a single line.

Possibly related PRs

  • route error fix #18: Modifies the health check endpoint (GET /health), related to the main PR's changes.
  • feature/auth #33: Involves changes to the route.ts file, including the GET /health endpoint, indicating a connection to the main PR.
  • auth #34: Similar modifications to route.ts, linking it to the health check endpoint changes in the main PR.
  • Feature/backend #55: Discusses the route.ts file where the health check endpoint is defined, showing a relationship with the main PR's changes.

🐇 In the code we hop and play,
With routes and emails on display.
From async to sync, we make the shift,
Dynamic imports give our code a lift!
A route renamed, a health check bright,
Hooray for changes, all feels just right! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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

vercel bot commented Nov 21, 2024

@wtfdivyansh is attempting to deploy a commit to the BlueFinZ Team on Vercel.

A member of the Team first needs to authorize it.

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

🧹 Outside diff range and nitpick comments (3)
apps/api/app/api/[[...route]]/health.ts (1)

Line range hint 3-8: Consider enhancing the health check response.

While the current implementation is functional, consider adding more useful health information such as:

  • API version
  • Environment
  • Uptime
  • Dependencies status (if any)
 app.get("/", (c) => {
   return c.json({
     message: "i am alive",
     status: 200,
+    version: process.env.npm_package_version,
+    env: process.env.NODE_ENV,
+    uptime: process.uptime(),
   });
 });
apps/api/app/api/[[...route]]/route.ts (1)

6-6: Consider renaming the import to match its purpose

The import name test doesn't align well with its usage in the /hello route. Consider renaming either:

  • The module file from test.ts to hello.ts, or
  • The import variable to better reflect its purpose
-import test from "./test";
+import hello from "./test";
apps/api/app/api/[[...route]]/mail.ts (1)

Line range hint 1-65: Consider implementing rate limiting and queuing

For a production email service, consider implementing:

  1. Rate limiting to prevent abuse
  2. Message queuing for better scalability
  3. Circuit breaker pattern for external email service failures

These patterns would make the email service more robust and scalable. Would you like guidance on implementing these architectural improvements?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 41525c6 and b26c867.

📒 Files selected for processing (3)
  • apps/api/app/api/[[...route]]/health.ts (1 hunks)
  • apps/api/app/api/[[...route]]/mail.ts (2 hunks)
  • apps/api/app/api/[[...route]]/route.ts (2 hunks)
🔇 Additional comments (1)
apps/api/app/api/[[...route]]/health.ts (1)

Line range hint 3-8: LGTM! Removing unnecessary async improves performance.

Converting the handler from async to sync is the right choice since there are no async operations in the implementation. This eliminates the unnecessary overhead of promise creation and async function invocation.

@@ -38,7 +38,7 @@ app.use(

app.route("/health", health);
app.route("/session", session);
app.route("/test", hello);
app.route("/hello", test);
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Renaming test route to hello is intentional but implementation needs alignment

The route change from /test to /hello is actually intentional as evidenced by the test file (hello.test.ts) which consistently uses /hello endpoint for testing user operations. However, there's a mismatch between:

  • The route name (/hello)
  • The handler file name (test.ts)
  • The handler's functionality (user operations)

Suggested changes:

  • Rename test.ts to users.ts or hello.ts to better reflect its purpose
  • Update the import statement accordingly
  • Consider renaming the route to /users to match the actual functionality
🔗 Analysis chain

Verify the intent of renaming test route to hello

There's an inconsistency between:

  • The module name (test)
  • The route path (/hello)
  • The handler variable name (test)

This makes the code less maintainable. Please verify if this was intentional and consider aligning these names.


Let me gather more information about the route handler and its usage.


Let me check the content of the test handler file and the test file to understand the full context.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the contents and usage of the test module to understand its purpose

# Check the implementation of the test module
echo "Checking test module implementation:"
cat apps/api/app/api/test.ts || echo "File not found"

# Look for any references to the old route
echo -e "\nChecking for references to old route path:"
rg -l "/test" --type ts

Length of output: 373


Script:

#!/bin/bash
# Check the content of the route file to understand the context
echo "Checking route file content:"
cat "apps/api/app/api/[[...route]]/route.ts"

# Look for any test-related files that might contain the handler
echo -e "\nLooking for test-related files:"
fd -t f -e ts test

# Search for 'test' function/variable declarations
echo -e "\nSearching for test handler definition:"
ast-grep --pattern 'const test = $_'

Length of output: 1670


Script:

#!/bin/bash
# Check the test handler implementation
echo "Checking test handler implementation:"
cat "apps/api/app/api/[[...route]]/test.ts"

# Check the test file content
echo -e "\nChecking test file content:"
cat "apps/api/tests/hello.test.ts"

Length of output: 3285

@@ -8,6 +7,7 @@ const app = new Hono();
app
.post("/send", zValidator("json", mailSchema), async (c) => {
const { email, subject } = c.req.valid("json");
const { sendEmail } = await import("@repo/mail");
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider caching the dynamic import result

The dynamic import is executed on every request, which could introduce unnecessary latency. Additionally, the import failure isn't explicitly handled.

Consider moving the import outside the route handler and implementing proper error handling:

+let sendEmailFn: typeof import("@repo/mail")["sendEmail"] | null = null;
+
 app
   .post("/send", zValidator("json", mailSchema), async (c) => {
     const { email, subject } = c.req.valid("json");
-    const { sendEmail } = await import("@repo/mail");
+    try {
+      if (!sendEmailFn) {
+        const { sendEmail } = await import("@repo/mail");
+        sendEmailFn = sendEmail;
+      }
+      const { data, error } = await sendEmailFn(email, subject);
+    } catch (importError) {
+      return c.json(
+        {
+          message: "Email service initialization failed",
+        },
+        500
+      );
+    }

Committable suggestion skipped: line range outside the PR's diff.

@@ -35,6 +35,7 @@
app
.post("/send-batch", zValidator("json", mailBatchSchema), async (c) => {
const { emails, subject } = c.req.valid("json");
const { sendBatchEmail } = await import("@repo/mail");
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Apply similar caching pattern and improve error messages

The dynamic import pattern is duplicated here and could benefit from the same caching approach. Additionally, the error messages could be more specific for batch operations.

Consider implementing similar caching and improving error messages:

+let sendBatchEmailFn: typeof import("@repo/mail")["sendBatchEmail"] | null = null;
+
 app
   .post("/send-batch", zValidator("json", mailBatchSchema), async (c) => {
     const { emails, subject } = c.req.valid("json");
-    const { sendBatchEmail } = await import("@repo/mail");
+    try {
+      if (!sendBatchEmailFn) {
+        const { sendBatchEmail } = await import("@repo/mail");
+        sendBatchEmailFn = sendBatchEmail;
+      }
+      const { data, error } = await sendBatchEmailFn(emails, subject);
+      if (error) {
+        return c.json(
+          {
-            message: "Email sent failed",
+            message: "Batch email operation failed",
+            error: error.message
+          },
+          400
+        );
+      }
+    } catch (importError) {
+      return c.json(
+        {
+          message: "Email service initialization failed",
+        },
+        500
+      );
+    }

Committable suggestion skipped: line range outside the PR's diff.

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

🧹 Outside diff range and nitpick comments (3)
apps/api/app/api/[[...route]]/auth.ts (1)

5-5: Consider using Hono's request context instead of raw request

Using c.req.raw bypasses Hono's built-in request parsing and middleware capabilities. Consider leveraging Hono's request context features unless there's a specific reason to use the raw request.

apps/api/app/api/[[...route]]/test.ts (1)

Line range hint 4-8: Consider adding pagination and access control

The current implementation has potential security and performance concerns:

  1. It exposes all user data without authentication/authorization
  2. No pagination could lead to performance issues with large datasets

Consider implementing:

  1. Authentication middleware
  2. Pagination with limit/offset or cursor-based approach
-const app = new Hono().get("/", async (c) => {
-  const user = await prisma.user.findMany();
-  return c.json({
-    user,
-  });
-});
+const app = new Hono().get("/", async (c) => {
+  const page = parseInt(c.req.query('page') || '1');
+  const limit = parseInt(c.req.query('limit') || '10');
+  const skip = (page - 1) * limit;
+
+  const [users, total] = await Promise.all([
+    prisma.user.findMany({
+      take: limit,
+      skip: skip,
+      select: {
+        id: true,
+        name: true,
+        email: true,
+        // Add other safe-to-expose fields
+      }
+    }),
+    prisma.user.count()
+  ]);
+
+  return c.json({
+    users,
+    pagination: {
+      total,
+      page,
+      limit,
+      pages: Math.ceil(total / limit)
+    }
+  });
+});
apps/api/app/api/[[...route]]/status.ts (1)

4-23: Consider implementing response caching.

Since status data likely doesn't need to be real-time, consider implementing response caching to reduce Redis load.

You could:

  1. Use Hono's built-in cache middleware
  2. Set appropriate cache headers
  3. Implement an in-memory cache with a short TTL

Example implementation:

import { cache } from 'hono/cache'

const app = new Hono()
  .use('/*', cache({
    cacheName: 'status-cache',
    cacheControl: 'max-age=10', // Cache for 10 seconds
  }))
  // ... rest of your routes
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b26c867 and 90e17b9.

📒 Files selected for processing (7)
  • apps/api/app/api/[[...route]]/auth.ts (1 hunks)
  • apps/api/app/api/[[...route]]/health.ts (1 hunks)
  • apps/api/app/api/[[...route]]/mail.ts (2 hunks)
  • apps/api/app/api/[[...route]]/route.ts (2 hunks)
  • apps/api/app/api/[[...route]]/session.ts (1 hunks)
  • apps/api/app/api/[[...route]]/status.ts (1 hunks)
  • apps/api/app/api/[[...route]]/test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/api/app/api/[[...route]]/health.ts
  • apps/api/app/api/[[...route]]/mail.ts
  • apps/api/app/api/[[...route]]/route.ts
🔇 Additional comments (6)
apps/api/app/api/[[...route]]/auth.ts (1)

4-6: Consider security implications of wildcard route pattern

The use of "/**" as a route pattern will match all paths under this route, which might be too permissive. Consider:

  1. Being more explicit about the exact paths that should be handled
  2. Adding method-specific logic for POST and GET requests

Suggested Implementation:

-const app = new Hono().on(["POST", "GET"], "/**", (c) => {
-  return auth.handler(c.req.raw);
-});
+const app = new Hono()
+  .get("/*", (c) => {
+    // Add GET-specific validation/logic here
+    return auth.handler(c.req.raw);
+  })
+  .post("/*", (c) => {
+    // Add POST-specific validation/logic here
+    return auth.handler(c.req.raw);
+  });
apps/api/app/api/[[...route]]/test.ts (2)

Line range hint 4-8: LGTM! Code structure improvement

The combined Hono instance creation with route definition improves code conciseness while maintaining readability.


Line range hint 4-8: Verify error handling in the database query

Ensure proper error handling for database operations to prevent exposing internal errors to clients.

Let's check if there's error handling middleware or similar patterns in other routes:

apps/api/app/api/[[...route]]/session.ts (2)

1-4: LGTM! Clean imports and initialization

The imports are properly structured and the app initialization using method chaining is clean.


2-2: Verify consistent auth package usage across routes

Let's verify if other routes follow similar authentication patterns.

✅ Verification successful

Let me gather more information about the auth package usage patterns to ensure a comprehensive verification.


Let me check how the auth package is used in the other files where it's imported to ensure consistency.


Auth package usage is consistent across routes

The verification shows consistent and proper usage of the @repo/auth package across the codebase:

  • session.ts correctly uses auth.api methods for session management
  • auth.ts properly handles authentication using auth.handler
  • route.ts correctly imports auth types for type inference
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for auth package usage patterns in route handlers
echo "Checking auth package usage patterns in routes:"
rg -A 5 "auth\.api\.(getSession|listDeviceSessions)" "apps/api/app/api"

Length of output: 983


Script:

#!/bin/bash
# Search for all auth package imports and usages
echo "Checking auth package imports:"
rg "import.*from.*@repo/auth" "apps/api"

echo -e "\nChecking all auth package method calls:"
rg "auth\.api\." "apps/api"

Length of output: 678


Script:

#!/bin/bash
# Check contents of other files using auth package
echo "Content of route.ts:"
cat "apps/api/app/api/[[...route]]/route.ts"

echo -e "\nContent of auth.ts:"
cat "apps/api/app/api/[[...route]]/auth.ts"

Length of output: 1618

apps/api/app/api/[[...route]]/status.ts (1)

1-4: LGTM! Clean setup with proper imports.

The initialization is well-structured and follows Hono's best practices.

Comment on lines +5 to +13
.get("/", async (c) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });

app.get("/", async (c) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) return c.json({ message: "no session found" }, 401);

if (!session) return c.json({ message: "no session found" }, 401);

return c.json({
session,
});
});

app.get("/all", async (c) => {
const res = await auth.api.listDeviceSessions({
headers: c.req.raw.headers,
return c.json({
session,
});
})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for auth API calls

While the session check logic is correct, the handler should include error handling for potential auth API failures.

Consider implementing error handling:

 .get("/", async (c) => {
+  try {
     const session = await auth.api.getSession({ headers: c.req.raw.headers });
     
     if (!session) return c.json({ message: "no session found" }, 401);
 
     return c.json({
       session,
     });
+  } catch (error) {
+    console.error('Session verification failed:', error);
+    return c.json({ message: "Internal server error" }, 500);
+  }
 })
📝 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
.get("/", async (c) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
app.get("/", async (c) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) return c.json({ message: "no session found" }, 401);
if (!session) return c.json({ message: "no session found" }, 401);
return c.json({
session,
});
});
app.get("/all", async (c) => {
const res = await auth.api.listDeviceSessions({
headers: c.req.raw.headers,
return c.json({
session,
});
})
.get("/", async (c) => {
try {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) return c.json({ message: "no session found" }, 401);
return c.json({
session,
});
} catch (error) {
console.error('Session verification failed:', error);
return c.json({ message: "Internal server error" }, 500);
}
})

Comment on lines +14 to +18
.get("/all", async (c) => {
const res = await auth.api.listDeviceSessions({
headers: c.req.raw.headers,
});
return c.json(res);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add session check and error handling for device sessions listing

The endpoint needs two improvements:

  1. Verify active session before listing devices
  2. Add error handling for API calls

Consider implementing these security and reliability improvements:

 .get("/all", async (c) => {
+  try {
+    const session = await auth.api.getSession({ headers: c.req.raw.headers });
+    
+    if (!session) return c.json({ message: "no session found" }, 401);
+
     const res = await auth.api.listDeviceSessions({
       headers: c.req.raw.headers,
     });
     return c.json(res);
+  } catch (error) {
+    console.error('Device sessions listing failed:', error);
+    return c.json({ message: "Internal server error" }, 500);
+  }
 });
📝 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
.get("/all", async (c) => {
const res = await auth.api.listDeviceSessions({
headers: c.req.raw.headers,
});
return c.json(res);
.get("/all", async (c) => {
try {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) return c.json({ message: "no session found" }, 401);
const res = await auth.api.listDeviceSessions({
headers: c.req.raw.headers,
});
return c.json(res);
} catch (error) {
console.error('Device sessions listing failed:', error);
return c.json({ message: "Internal server error" }, 500);
}

Comment on lines +5 to +12
.get("/", async (c) => {
const dbStatus = await cache.lrange("db-latency:history", 0, -1);
const siteStatus = await cache.lrange("site-latency:history", 0, -1);
return c.json({
dbStatus,
siteStatus,
});
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for cache operations.

The cache operations could fail and should be wrapped in try-catch blocks to handle potential Redis errors gracefully.

Here's a suggested implementation:

  .get("/", async (c) => {
+   try {
      const dbStatus = await cache.lrange("db-latency:history", 0, -1);
      const siteStatus = await cache.lrange("site-latency:history", 0, -1);
      return c.json({
        dbStatus,
        siteStatus,
      });
+   } catch (error) {
+     return c.json({ error: "Failed to fetch status" }, 500);
+   }
  })
📝 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
.get("/", async (c) => {
const dbStatus = await cache.lrange("db-latency:history", 0, -1);
const siteStatus = await cache.lrange("site-latency:history", 0, -1);
return c.json({
dbStatus,
siteStatus,
});
})
.get("/", async (c) => {
try {
const dbStatus = await cache.lrange("db-latency:history", 0, -1);
const siteStatus = await cache.lrange("site-latency:history", 0, -1);
return c.json({
dbStatus,
siteStatus,
});
} catch (error) {
return c.json({ error: "Failed to fetch status" }, 500);
}
})

Comment on lines +13 to +23
.get("/db", async (c) => {
const dbStatus = await cache.lrange("db-latency:history", 0, -1);
return c.json({
dbStatus,
});
})
.get("/site", async (c) => {
const siteStatus = await cache.lrange("site-latency:history", 0, -1);
return c.json({
siteStatus,
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor repeated logic and add error handling.

Both route handlers share similar patterns and would benefit from:

  1. Error handling for cache operations
  2. A shared middleware for common cache operations

Here's a suggested implementation:

+ const fetchCacheData = async (key: string) => {
+   try {
+     return await cache.lrange(key, 0, -1);
+   } catch (error) {
+     throw new Error(`Failed to fetch ${key}`);
+   }
+ };

+ const withErrorHandler = async (c: Context, handler: () => Promise<Response>) => {
+   try {
+     return await handler();
+   } catch (error) {
+     return c.json({ error: error.message }, 500);
+   }
+ };

  .get("/db", async (c) => {
+   return withErrorHandler(c, async () => {
-     const dbStatus = await cache.lrange("db-latency:history", 0, -1);
+     const dbStatus = await fetchCacheData("db-latency:history");
      return c.json({ dbStatus });
+   });
  })
  .get("/site", async (c) => {
+   return withErrorHandler(c, async () => {
-     const siteStatus = await cache.lrange("site-latency:history", 0, -1);
+     const siteStatus = await fetchCacheData("site-latency:history");
      return c.json({ siteStatus });
+   });
  });
📝 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
.get("/db", async (c) => {
const dbStatus = await cache.lrange("db-latency:history", 0, -1);
return c.json({
dbStatus,
});
})
.get("/site", async (c) => {
const siteStatus = await cache.lrange("site-latency:history", 0, -1);
return c.json({
siteStatus,
});
const fetchCacheData = async (key: string) => {
try {
return await cache.lrange(key, 0, -1);
} catch (error) {
throw new Error(`Failed to fetch ${key}`);
}
};
const withErrorHandler = async (c: Context, handler: () => Promise<Response>) => {
try {
return await handler();
} catch (error) {
return c.json({ error: error.message }, 500);
}
};
.get("/db", async (c) => {
return withErrorHandler(c, async () => {
const dbStatus = await fetchCacheData("db-latency:history");
return c.json({ dbStatus });
});
})
.get("/site", async (c) => {
return withErrorHandler(c, async () => {
const siteStatus = await fetchCacheData("site-latency:history");
return c.json({ siteStatus });
});
});

@SkidGod4444 SkidGod4444 merged commit a54aef5 into SkidGod4444:main Nov 21, 2024
3 of 5 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.

2 participants