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] Save language preference in database #2043

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

Conversation

enzogms
Copy link

@enzogms enzogms commented Feb 26, 2025

Closes 2013

Copy link

vercel bot commented Feb 26, 2025

@enzogms is attempting to deploy a commit to the Typebot Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented Feb 26, 2025

Walkthrough

The changes refactor how user locale preferences are handled across the application. In the client-side form, the updateLocale function now calls updateUser with the selected locale instead of setting a cookie. On the server side, both the index and typebots pages have updated session casting and now compute a preferredLanguagePath for redirection based on the user's language preference. Additionally, the user schema is extended in both the Prisma model and the Zod schema to include a new optional (or nullable) preferredLanguage field.

Changes

File(s) Change Summary
apps/builder/.../UserPreferencesForm.tsx Modified updateLocale: removed cookie setting and now calls updateUser({ preferredLanguage }); router replace logic remains unchanged.
apps/builder/.../(index.tsx, typebots.tsx) Updated session retrieval to cast with User type; introduced preferredLanguagePath variable to determine redirect destination based on the user's preferred language.
packages/prisma/.../schema.prisma,
packages/schemas/.../schema.ts
Added a new preferredLanguage field for the User model: optional with default "en" in Prisma and nullable string in the Zod schema.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant F as UserPreferencesForm
    participant A as updateUser
    participant R as Router

    U->>F: Selects language preference
    F->>A: Calls updateUser({ preferredLanguage })
    A-->>F: Returns updated state
    F->>R: Replaces route with updated path
Loading
sequenceDiagram
    participant Req as Request
    participant SS as Server (getServerSideProps)
    participant GS as getServerSession
    participant RL as Redirect Logic

    Req->>SS: Initiates request
    SS->>GS: Retrieve session (with User and preferredLanguage)
    GS-->>SS: Returns session data
    SS->>RL: Compute preferredLanguagePath
    RL-->>SS: Returns computed language path
    SS->>Req: Issues redirect using computed path
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

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 generate docstrings to generate docstrings for 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

@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 (2)
apps/builder/src/pages/typebots.tsx (2)

19-19: Remove debugging console log before production.

This debug log statement should be removed before merging to production. While helpful during development, it could expose sensitive user information in logs.

- console.log("🚀 ~ session:", session);

14-27: Consider extracting the language preference logic to a utility function.

This language preference determination logic might be reused across different pages. Consider extracting it to a shared utility function to avoid duplication and improve maintainability.

// Proposed utility in a shared location (e.g., src/utils/language.ts)
export const getPreferredLanguagePath = (
  user: User | undefined,
  contextLocale: string | undefined,
  defaultLocale: string | undefined
): string | undefined => {
  return user?.preferredLanguage && user.preferredLanguage !== defaultLocale
    ? user.preferredLanguage
    : contextLocale !== defaultLocale
      ? contextLocale
      : undefined;
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 734ace2 and dc35eeb.

📒 Files selected for processing (2)
  • apps/builder/src/pages/index.tsx (3 hunks)
  • apps/builder/src/pages/typebots.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/builder/src/pages/index.tsx
🔇 Additional comments (4)
apps/builder/src/pages/typebots.tsx (4)

1-1: Import additions look good.

The additional imports support the new user language preference functionality. The User type is correctly imported from the schemas package, and the session-related imports from next-auth are appropriate for server-side session handling.

Also applies to: 3-3, 5-5


14-18: Session retrieval implementation is correct.

The implementation properly retrieves the server session and casts it to include the user with their preferences. This allows access to the user's preferred language property for the redirection logic.


21-27: Language preference logic is well-implemented.

The logic correctly prioritizes:

  1. User's stored preferred language (if set and different from default)
  2. Request context locale (if different from default)
  3. Falls back to undefined when appropriate

The null-safety with optional chaining is properly implemented.


39-41: Redirect path construction looks good.

The conditional path construction properly incorporates the preferred language into the URL structure when available, maintaining the original redirect functionality when not.

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 (3)
apps/builder/src/pages/typebots.tsx (3)

14-18: Consider using type guards instead of type assertion.

The type assertion as Session & { user: User } works but could be more safely handled with proper type guards.

- const session = (await getServerSession(
-   context.req,
-   context.res,
-   createAuthConfig({}),
- )) as Session & { user: User };
+ const session = await getServerSession(
+   context.req,
+   context.res,
+   createAuthConfig({}),
+ );
+ 
+ // Type guard to ensure session and user exist
+ const userSession = session && 'user' in session ? 
+   { ...session, user: session.user as User } : null;

38-40: Consider adding error handling for URL construction.

The URL construction works as implemented, but consider adding error handling for malformed paths or using a URL construction utility for more robustness.

- destination: preferredLanguagePath
-   ? `/${preferredLanguagePath}/${redirectPath}`
-   : `/${redirectPath}`,
+ destination: preferredLanguagePath
+   ? `/${preferredLanguagePath}/${redirectPath.startsWith('/') ? redirectPath.substring(1) : redirectPath}`
+   : `/${redirectPath.startsWith('/') ? redirectPath.substring(1) : redirectPath}`,

14-40: Add error handling for session retrieval.

There's no error handling for the getServerSession call. If session retrieval fails, it might cause unexpected behavior.

- const session = (await getServerSession(
-   context.req,
-   context.res,
-   createAuthConfig({}),
- )) as Session & { user: User };
+ let session;
+ try {
+   session = (await getServerSession(
+     context.req,
+     context.res,
+     createAuthConfig({}),
+   )) as Session & { user: User };
+ } catch (error) {
+   console.error('Failed to retrieve session:', error);
+   // Provide fallback behavior or decide how to handle the error
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dc35eeb and d66a612.

📒 Files selected for processing (1)
  • apps/builder/src/pages/typebots.tsx (3 hunks)
🔇 Additional comments (3)
apps/builder/src/pages/typebots.tsx (3)

3-3: Clean import of the User type.

The User type import is appropriately added to support the new language preference feature.


5-5: Good addition of next-auth imports.

Properly importing both the Session type and getServerSession function for authentication handling.


20-26: Good implementation of preferred language logic.

This logic correctly determines the language path by checking the user's preferred language first, then falling back to context locale if needed.

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.

Save language preference in database
1 participant