Skip to content

fix: organization setup redirect if it didn't create correctly#309

Merged
carhartlewis merged 2 commits into
mainfrom
lewis/timeout
Apr 6, 2025
Merged

fix: organization setup redirect if it didn't create correctly#309
carhartlewis merged 2 commits into
mainfrom
lewis/timeout

Conversation

@carhartlewis
Copy link
Copy Markdown
Contributor

@carhartlewis carhartlewis commented Apr 6, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced dashboard performance through improved data retrieval, ensuring a more responsive experience.
    • Upgraded organization verification that directs users appropriately during setup for seamless access.
  • Refactor

    • Streamlined session management and page rendering logic across dashboard and setup areas, resulting in a cleaner and more maintainable flow.

@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 6, 2025

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

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
app ⬜️ Skipped (Inspect) Apr 6, 2025 3:01am
comp-portal ⬜️ Skipped (Inspect) Apr 6, 2025 3:01am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 6, 2025

Walkthrough

This pull request refactors two framework instance functions by converting them from asynchronous function declarations to exported constants wrapped with a caching mechanism. Additionally, a new, cached asynchronous function (getOrganization) is introduced in the layout to validate and fetch organization data, with error handling to trigger redirects on failure. Minor formatting improvements are also applied in the dashboard and setup pages to enhance code readability without altering core functionality.

Changes

File(s) Change Summary
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getAllFrameworkInstancesWithControls.ts
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getSingleFrameworkInstanceWithControls.ts
Converted async functions to exported constants wrapped with a caching mechanism, preserving function signatures and internal logic.
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/page.tsx Adjusted formatting and updated an import path for improved clarity and maintainability.
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/layout.tsx Added a cached asynchronous getOrganization function with error handling and updated control flow to validate organization data and handle redirects.
apps/app/src/app/[locale]/(app)/setup/page.tsx Streamlined session and organization handling by removing an unnecessary active organization ID check and reorganizing the code flow.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Layout
    participant getOrganization
    participant Database
    Client->>Layout: Request layout with orgId
    Layout->>getOrganization: Validate organization (using cache)
    getOrganization->>Database: Query organization data
    Database-->>getOrganization: Return data or error
    getOrganization-->>Layout: Return organization data
    alt Organization valid
      Layout->>Client: Render dashboard layout
    else Organization invalid or error
      Layout->>Client: Redirect to "/setup"
    end
Loading

Possibly related PRs

Poem

I hopped through code with a joyful heart,
Caching functions to give them a brand-new start.
With getOrganization guarding our way,
I skipped past bugs without delay.
In formatted lines, the code now sings—
A bouncy delight from your coding rabbit! 🐰

✨ 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.
    • 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 plan to trigger planning for file edits and PR creation.
  • @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 (5)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/page.tsx (1)

25-25: Consider removing console.log statement.

Debug logs like this one should be removed before merging to production.

-    console.log("Redirect on page.tsx");
apps/app/src/app/[locale]/(app)/setup/page.tsx (1)

30-38: Add a comment explaining the redirect condition logic.

The condition checks if the active organization isn't set in the session but an organization exists in the database. This logic might not be immediately clear to other developers.

+  // If user has an organization but it's not set as active in their session,
+  // set it as active and redirect to the organization's frameworks page
   if (!session?.session?.activeOrganizationId && organization?.id) {
     await auth.api.setActiveOrganization({
       headers: headersList,
       body: {
         organizationId: organization.id,
       },
     });
     redirect(`/${organization.id}/frameworks`);
   }
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/layout.tsx (3)

20-26: Type definition improvement.

The params type is defined as a Promise, which is unusual for Next.js route parameters. While this works, it would be clearer to define it as a direct object type.

export default async function Layout({
  children,
  params,
}: {
  children: React.ReactNode;
-  params: Promise<{ orgId: string }>;
+  params: { orgId: string };
}) {

58-75: Well-implemented cached organization validation function.

The getOrganization function:

  • Uses React's cache mechanism to avoid duplicate database queries
  • Properly handles database errors with a try/catch block
  • Includes appropriate redirects to the setup page when an organization doesn't exist

Consider adding TypeScript return type annotation for better type safety.

-const getOrganization = cache(async (orgId: string) => {
+const getOrganization = cache(async (orgId: string): Promise<{ id: string; [key: string]: any }> => {

58-75: Enhanced error handling opportunity.

While the error handling redirects users appropriately, logging only displays the error without context. Consider enhancing the error logging to include the orgId for easier debugging.

  } catch (error) {
-    console.error(error);
+    console.error(`Error fetching organization with ID ${orgId}:`, error);
    redirect("/setup");
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d9b8916 and baafe71.

📒 Files selected for processing (5)
  • apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getAllFrameworkInstancesWithControls.ts (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getSingleFrameworkInstanceWithControls.ts (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/page.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/layout.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/setup/page.tsx (1 hunks)
🧰 Additional context used
🧬 Code Definitions (5)
apps/app/src/app/[locale]/(app)/setup/page.tsx (2)
apps/app/src/app/[locale]/(app)/setup/components/accept-invite.tsx (1)
  • AcceptInvite (9-55)
apps/app/src/components/forms/create-organization-form.tsx (1)
  • OnboardingClient (33-218)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/page.tsx (4)
apps/app/src/utils/auth.ts (1)
  • auth (11-86)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getAllFrameworkInstancesWithControls.ts (1)
  • getAllFrameworkInstancesWithControls (7-34)
apps/app/src/components/pages/PageWithBreadcrumb.tsx (1)
  • PageWithBreadcrumb (42-135)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/components/FrameworksOverview.tsx (1)
  • FrameworksOverview (9-26)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/layout.tsx (3)
apps/app/src/utils/auth.ts (1)
  • auth (11-86)
apps/app/src/components/sidebar.tsx (1)
  • Sidebar (10-56)
apps/app/src/components/header.tsx (1)
  • Header (16-66)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getAllFrameworkInstancesWithControls.ts (1)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/types.ts (1)
  • FrameworkInstanceWithControls (10-18)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getSingleFrameworkInstanceWithControls.ts (1)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/types.ts (1)
  • FrameworkInstanceWithControls (10-18)
🔇 Additional comments (10)
apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/page.tsx (4)

5-5: Good change to use absolute imports.

Converting from relative to absolute import path for PageWithBreadcrumb improves maintainability and readability.


10-14: Improved formatting of metadata.

The consistent indentation in the generateMetadata function enhances code readability.


18-20: Clean formatting of session retrieval.

The adjusted indentation makes the session retrieval code more consistent with the rest of the codebase.


33-37: Well-formatted return statement.

The adjusted indentation in the return statement improves code readability.

apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getSingleFrameworkInstanceWithControls.ts (1)

3-3: Great optimization with React cache.

Using React's cache function to memoize database queries is an excellent performance optimization. It will prevent redundant database calls when the function is called multiple times with the same parameters across rendering cycles.

Also applies to: 7-37

apps/app/src/app/[locale]/(app)/setup/page.tsx (1)

20-28: Good improvement to explicitly fetch the organization.

Explicitly fetching the organization from the database rather than relying solely on the session state is a more robust approach. This ensures the organization actually exists in the database before attempting to redirect.

apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/frameworks/data/getAllFrameworkInstancesWithControls.ts (1)

3-3: Great performance optimization with React cache.

Using React's cache function to memoize database queries is an excellent optimization. It will prevent redundant database calls when this function is called multiple times with the same organizationId parameter across rendering cycles.

This is consistent with the same optimization applied to getSingleFrameworkInstanceWithControls.

Also applies to: 7-34

apps/app/src/app/[locale]/(app)/(dashboard)/[orgId]/layout.tsx (3)

7-11: Good addition of required imports.

The new imports for db from "@comp/db" and cache from "react" are correctly added to support the new organization validation functionality.


27-42: Good session validation and organization redirection flow.

The code correctly:

  1. Retrieves the session using auth headers
  2. Extracts the orgId from params
  3. Validates the organization exists via getOrganization
  4. Checks authentication status with proper redirects

This refactored flow ensures users can't access invalid organization pages.


31-32:

Details

✅ Verification successful

Verify params unwrapping.

The params object is being treated as a Promise with await, but depending on Next.js version and configuration, it might already be a plain object. If it's consistently a Promise, this is correct.


🏁 Script executed:

#!/bin/bash
# Look for similar patterns in other route handlers to verify consistency
rg -A 2 -B 2 "params.*orgId" --glob "*.tsx" --glob "*.ts" | grep -v "Promise"

Length of output: 5653


Review Approved: Params Unwrapping Is Consistent

After reviewing similar route handler files across the codebase (e.g., in layout and page components), it’s clear that using await params is a consistent pattern. Given that Next.js may return params as a Promise in these contexts, the usage in:

const orgId = (await params).orgId;
await getOrganization(orgId);

is valid and aligns with our implementation strategy. No changes are needed.

@vercel vercel Bot temporarily deployed to Preview – comp-portal April 6, 2025 03:01 Inactive
@vercel vercel Bot temporarily deployed to Preview – app April 6, 2025 03:01 Inactive
@carhartlewis carhartlewis merged commit e17a7ec into main Apr 6, 2025
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