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

fixing fetch link #24

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open

fixing fetch link #24

wants to merge 11 commits into from

Conversation

SanjanaSogimatt
Copy link
Collaborator

@SanjanaSogimatt SanjanaSogimatt commented Nov 14, 2024

📋 Description

Adding fetch url

Summary by CodeRabbit

  • New Features

    • Improved error reporting in the email sending process, now returning error messages directly in the response.
    • Enhanced URL construction for API requests in the contact form, simplifying the process.
    • Feedback for users now includes displayed formUrl and fetchResponse variables in the form submission.
  • Bug Fixes

    • Streamlined error message handling for form submissions to provide a consistent user experience.
  • Chores

    • Removed unnecessary variables related to pricing from the programs page, focusing on relevant program data.

Copy link

cloudflare-workers-and-pages bot commented Nov 14, 2024

Deploying amrit with  Cloudflare Pages  Cloudflare Pages

Latest commit: 267f99c
Status: ✅  Deploy successful!
Preview URL: https://750d7f23.amrit.pages.dev
Branch Preview URL: https://feat-contact-us.amrit.pages.dev

View logs

Copy link

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes in this pull request involve updates to error handling and response logic in the sendEmail API route, alongside modifications to the form submission process in the contact.astro file. The error handling mechanism is enhanced to include error messages directly in the response. Additionally, the construction of the request URL for sending emails is simplified. The pricing variable is removed from the programs.astro file, streamlining the data used in the <Base> component.

Changes

File Change Summary
src/pages/api/sendEmail.ts Modified error handling to encapsulate email sending in a try block; error messages included in the response.
src/pages/contact.astro Introduced formUrl for API endpoint and fetchResponse for error handling; updated URL construction and response parsing.
src/pages/programs.astro Removed pricing variable and updated <Base> attributes to use program data instead.

Possibly related PRs

  • adding about us page #14: The changes in the src/pages/contact.astro file involve error handling for the API request that sends emails, which is related to the email sending process updated in src/pages/api/sendEmail.ts.

🐇 "In the meadow where bunnies play,
We’ve tidied up the code today!
Errors now speak, no more to hide,
A clearer path for emails to glide.
With a hop and a skip, the changes are neat,
Let’s celebrate with a joyful tweet!" 🌼

Warning

Rate limit exceeded

@drtechie has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 51 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 8b55e18 and 267f99c.


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

@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 and nitpick comments (1)
src/pages/contact.astro (1)

24-24: Consider using structured logging.

While console.log(data) is helpful for debugging, consider using a more structured approach for better debugging and monitoring.

-    console.log(data)
+    console.log('[Contact Form Response]:', {
+      status: response.status,
+      data,
+      timestamp: new Date().toISOString()
+    });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f81a833 and 21c29c1.

📒 Files selected for processing (2)
  • src/pages/api/sendEmail.ts (0 hunks)
  • src/pages/contact.astro (1 hunks)
💤 Files with no reviewable changes (1)
  • src/pages/api/sendEmail.ts
🔇 Additional comments (1)
src/pages/contact.astro (1)

17-18: LGTM! URL construction looks correct.

The change from .href to .origin is appropriate as it ensures the base URL is used without path components, preventing potential double-path issues.

Let's verify the API endpoint accessibility:

✅ Verification successful

URL construction and API endpoint are properly aligned

The verification confirms:

  • The API endpoint exists at the correct path src/pages/api/sendEmail.ts
  • The endpoint is properly implemented as a POST route that handles form data
  • No other files are using a different endpoint pattern
  • Using .origin in the URL construction is correct as it matches the API route's location

The change from .href to .origin ensures proper URL construction without path duplication, and the endpoint is available at the expected location.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the sendEmail API endpoint exists and follows the expected pattern
# Expected: Find the API endpoint at /api/sendEmail

# Search for the API route file
fd -t f "sendEmail.ts" "src/pages/api"

# Verify the endpoint pattern in other areas of the codebase
rg -g '!contact.astro' "api/sendEmail" "src"

Length of output: 106


Script:

#!/bin/bash
# Let's examine the API endpoint implementation to ensure it matches the expected usage
cat src/pages/api/sendEmail.ts

# Also check if there are any other files that might be using a different endpoint pattern
rg -g '!contact.astro' "fetch.*sendEmail" src

Length of output: 1469

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

🧹 Outside diff range and nitpick comments (1)
src/pages/contact.astro (1)

27-39: Enhance error handling and user feedback.

While the error handling is more comprehensive, consider these improvements:

  1. The generic error message "Something went wrong" could be more specific based on the error type
  2. Consider handling other successful HTTP status codes (e.g., 201, 204)
  3. The "JSON parsing error" message isn't user-friendly

Here's a suggested improvement:

 try {
   const data = await response.json();
-  if (response.status === 200) {
+  if (response.ok) {  // This checks for status codes 200-299
     message = data.message;
     messageType = "success";
   } else {
-    message = "Something went wrong. Please try again.";
+    message = data.error || "Unable to send message. Please try again later.";
     messageType = "error";
   }
 } catch (e) {
-  message = "JSON parsing error";
+  message = "We're experiencing technical difficulties. Please try again later.";
   messageType = "error";
-  fetchResponse = await response.text();
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a66dfcf and 8b55e18.

📒 Files selected for processing (2)
  • src/pages/api/sendEmail.ts (1 hunks)
  • src/pages/contact.astro (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pages/api/sendEmail.ts
🔇 Additional comments (2)
src/pages/contact.astro (2)

19-20: Well-structured API endpoint URL construction!

Using URL(Astro.request.url).origin is a robust approach for constructing the API endpoint URL, making it work correctly across different environments.


19-20: Verify API endpoint usage across the codebase.

Let's ensure the API endpoint is consistently used across the codebase.

✅ Verification successful

API endpoint usage is localized to contact page

The sendEmail API endpoint is only used in src/pages/contact.astro and there are no other fetch calls in the codebase that need similar URL construction. The changes are self-contained and don't require modifications elsewhere.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other instances of sendEmail API usage
rg -l "sendEmail" --type astro --type typescript

# Look for other fetch calls that might need similar URL construction
rg "fetch\(" --type astro --type typescript

Length of output: 154


Script:

#!/bin/bash
# Search for sendEmail API usage without file type filters
rg -l "sendEmail"

# Look for fetch calls that might need similar URL construction
rg "fetch\(" -A 2

Length of output: 236

Comment on lines +14 to +15
let formUrl = ""
let fetchResponse = ""
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove debugging variables from production code.

The variables formUrl and fetchResponse appear to be used for debugging purposes. Exposing internal URLs and raw error responses to end users is not recommended in production code as it could reveal sensitive implementation details.

Remove these debug variables and their corresponding display in the UI.

Comment on lines +68 to +69
<p>{formUrl}</p>
<p>{fetchResponse}</p>
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove debug information from UI.

Displaying formUrl and fetchResponse in the UI exposes internal implementation details and potentially sensitive information to end users. This debug information should be removed from production code.

Remove these lines:

-              <p>{formUrl}</p>
-              <p>{fetchResponse}</p>
📝 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
<p>{formUrl}</p>
<p>{fetchResponse}</p>

Copy link

sonarcloud bot commented Nov 14, 2024

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

🧹 Outside diff range and nitpick comments (2)
src/pages/contact.astro (2)

27-42: Simplify error handling logic.

The current implementation with response cloning and nested try-catch blocks is overly complex. Consider simplifying it for better maintainability.

Here's a suggested refactor:

-    const clonedResponse = response.clone();
-    try {
-      const data = await response.json();
-      if (response.status === 200) {
-        message = data.message;
-        messageType = "success"; // Success
-      } else {
-        message = "Something went wrong. Please try again.";
-        messageType = "error"; // Failure
-      }
-    } catch (e) {
-      message = "JSON parsing error";
-      messageType = "error";
-      fetchResponse = await clonedResponse.text();
-    }
+    const data = response.ok 
+      ? await response.json().catch(() => ({ message: "Invalid response format" }))
+      : { message: "Something went wrong. Please try again." };
+    
+    message = data.message;
+    messageType = response.ok ? "success" : "error";

Line range hint 74-81: Add CSRF protection to the form.

The form handles sensitive user data but lacks CSRF protection. Consider adding a CSRF token to prevent cross-site request forgery attacks.

Implement CSRF protection by:

  1. Generating a CSRF token on the server side
  2. Including it as a hidden input in the form
  3. Validating the token in the API endpoint

Example implementation:

+ <input type="hidden" name="csrf_token" value={generateCSRFToken()} />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8b55e18 and 267f99c.

📒 Files selected for processing (1)
  • src/pages/contact.astro (2 hunks)
🔇 Additional comments (2)
src/pages/contact.astro (2)

19-20: LGTM: Improved URL construction using request origin.

The URL construction using new URL(Astro.request.url).origin is a good practice as it makes the endpoint relative to the current environment.


69-70: Previous review comment is still applicable.

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