Skip to content

✨ Add space member model #1780

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
Jun 16, 2025
Merged

✨ Add space member model #1780

merged 3 commits into from
Jun 16, 2025

Conversation

lukevella
Copy link
Owner

@lukevella lukevella commented Jun 16, 2025

Summary by CodeRabbit

  • New Features

    • Introduced support for spaces and space memberships, allowing users to belong to multiple spaces with roles such as OWNER, ADMIN, or MEMBER.
    • Users can now view and manage their memberships across different spaces.
    • Added streamlined user creation process that automatically creates a personal space and assigns ownership.
    • Added ability to create new spaces with automatic owner membership assignment.
  • Bug Fixes

    • Ensured existing space owners are correctly assigned as members with the OWNER role.
  • Style

    • Improved formatting for better readability in user-related information.

✨ Space members migration
Copy link

vercel bot commented Jun 16, 2025

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

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 16, 2025 2:49pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
landing ⬜️ Skipped (Inspect) Jun 16, 2025 2:49pm

Copy link
Contributor

coderabbitai bot commented Jun 16, 2025

"""

Walkthrough

The changes introduce new database structures and relationships for managing spaces and their members. A new enum, tables, and models are added to represent spaces and memberships, with appropriate indexes and foreign key constraints. Existing spaces are backfilled with owner memberships. The user model is updated to support these new relationships. User creation logic is refactored to centralize creation with associated default personal space and membership.

Changes

Files/Paths Change Summary
.../migrations/20250616140319_create_space_members/migration.sql Adds SpaceMemberRole enum, creates space_members table, indexes, and foreign key constraints.
.../migrations/20250616140359_space_members_migration/migration.sql Inserts owner membership records into space_members for existing spaces, avoiding duplicates.
.../prisma/models/space.prisma Adds Space and SpaceMember models, SpaceMemberRole enum, relations, and constraints.
.../prisma/models/user.prisma Adds memberOf relation to User, removes Space model, reformats fields for readability.
apps/web/src/auth/adapters/prisma.ts Refactors createUser method to call new centralized createUser mutation function instead of direct Prisma call.
apps/web/src/features/spaces/mutations.ts Adds createSpace function to create a space with an owner member record.
apps/web/src/features/user/mutations.ts Adds createUser function that creates a user, a default "Personal" space, and membership within a transaction.
apps/web/src/trpc/routers/auth.ts Refactors user creation in authenticateRegistration mutation to use new createUser function and returns limited user fields.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthRouter
    participant UserMutations
    participant PrismaDB

    Client->>AuthRouter: authenticateRegistration(data)
    AuthRouter->>UserMutations: createUser(data)
    UserMutations->>PrismaDB: Begin transaction
    UserMutations->>PrismaDB: Create user record
    UserMutations->>PrismaDB: Create "Personal" space owned by user
    UserMutations->>PrismaDB: Create space member record with role OWNER
    UserMutations->>PrismaDB: Commit transaction
    UserMutations-->>AuthRouter: Return created user (id, name, email)
    AuthRouter-->>Client: Return user info
Loading
sequenceDiagram
    participant Client
    participant SpacesMutations
    participant PrismaDB

    Client->>SpacesMutations: createSpace({ownerId, name})
    SpacesMutations->>PrismaDB: Create space record
    SpacesMutations->>PrismaDB: Create space member record with role OWNER
    SpacesMutations-->>Client: Return created space
Loading

Possibly related PRs

Poem

🐇✨ In burrows deep where data flows,
New spaces bloom and membership grows.
Owners, admins, members aligned,
In tables and enums, all well-defined.
With hops and keys, relations spun,
Together they hop — the code’s just begun!
🌿📦
"""


📜 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 352f375 and f13b860.

📒 Files selected for processing (1)
  • apps/web/src/trpc/routers/auth.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/trpc/routers/auth.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Integration tests
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch space/members
  • Post Copyable Unit Tests in Comment

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 auto-generate unit tests to generate unit tests 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
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: 3

🧹 Nitpick comments (1)
packages/database/prisma/models/user.prisma (1)

61-63: Explicit relation naming for clarity
You’ve linked spaces Space[] @relation("UserSpaces") to match Space.owner. For memberOf SpaceMember[], consider adding an explicit @relation name (e.g. @relation("SpaceMemberToUser")) to tie it unambiguously to SpaceMember.user.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd9bdbc and 34e5498.

📒 Files selected for processing (4)
  • packages/database/prisma/migrations/20250616140319_create_space_members/migration.sql (1 hunks)
  • packages/database/prisma/migrations/20250616140359_space_members_migration/migration.sql (1 hunks)
  • packages/database/prisma/models/space.prisma (1 hunks)
  • packages/database/prisma/models/user.prisma (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Integration tests
🔇 Additional comments (5)
packages/database/prisma/models/space.prisma (2)

1-17: Relation and mapping fields look good
The Space model correctly maps snake-cased columns via @map, uses @default(uuid()) for IDs, and sets up the owner relation with onDelete: Cascade. Indexing ownerId with a hash is appropriate for fast owner‐space lookups.


19-23: Enum definition is correct
SpaceMemberRole enumerates exactly the roles needed (OWNER, ADMIN, MEMBER) with clear naming.

packages/database/prisma/migrations/20250616140319_create_space_members/migration.sql (3)

1-4: Enum creation is correct
The SpaceMemberRole enum is created before any table references it—order is correct.


16-21: Indexes and unique constraints are properly defined
You’ve added both the single‐column index on space_id and the unique composite index on (space_id, user_id), matching the Prisma schema’s intent.


23-27: Foreign keys with cascading actions look good
Both FK constraints include ON DELETE CASCADE and ON UPDATE CASCADE, ensuring referential integrity on space and user removals/updates.

@vercel vercel bot temporarily deployed to Preview – landing June 16, 2025 14:36 Inactive
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: 1

🧹 Nitpick comments (3)
apps/web/src/features/spaces/mutations.ts (2)

14-18: Avoid magic string for role – prefer the generated enum

Using a raw string literal makes refactors error-prone and bypasses type-safety. Leverage the generated Prisma enum instead:

-import { prisma } from "@rallly/database";
+import { prisma, SpaceMemberRole } from "@rallly/database";
...
-          role: "OWNER",
+          role: SpaceMemberRole.OWNER,

If SpaceMemberRole is re-exported from another module, import from that path instead.


3-9: Add lightweight validation for the public API surface

createSpace currently trusts its caller. A stray empty name or undefined ownerId would raise a DB error. Guard early (e.g. with a small Zod schema):

 export async function createSpace({
   ownerId,
   name,
 }: {
   ownerId: string;
   name: string;
 }) {
+  if (!ownerId) throw new Error("ownerId is required");
+  if (!name?.trim()) throw new Error("name cannot be empty");
+

This keeps boundary checks close to the mutation and returns clearer errors to the caller.

apps/web/src/features/user/mutations.ts (1)

22-53: Prefer enum constants over string literals for roles

Hard-coded role strings ("user" & "OWNER") sidestep compile-time checks. Import the generated enums:

-import { type TimeFormat, prisma } from "@rallly/database";
+import { type TimeFormat, prisma, SpaceMemberRole, UserRole } from "@rallly/database";
...
-        role: "user",
+        role: UserRole.USER,
...
-        role: "OWNER",
+        role: SpaceMemberRole.OWNER,

This prevents typos and guarantees sync with future schema changes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34e5498 and 352f375.

📒 Files selected for processing (4)
  • apps/web/src/auth/adapters/prisma.ts (2 hunks)
  • apps/web/src/features/spaces/mutations.ts (1 hunks)
  • apps/web/src/features/user/mutations.ts (1 hunks)
  • apps/web/src/trpc/routers/auth.ts (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
apps/web/src/auth/adapters/prisma.ts (1)
Learnt from: lukevella
PR: lukevella/rallly#1776
File: apps/web/src/auth/adapters/prisma.ts:40-60
Timestamp: 2025-06-14T16:32:39.947Z
Learning: In the Rallly authentication system, data migration (via options.migrateData) happens at login time, not during user creation. The createUser method in CustomPrismaAdapter should not call migrateData.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Integration tests
🔇 Additional comments (1)
apps/web/src/auth/adapters/prisma.ts (1)

42-50: Confirm type compatibility between createUser return and AdapterUser

createUser returns the raw Prisma User, which contains extra fields (role, etc.) that next-auth’s AdapterUser omits. Ensure downstream code (and JSON serialization) tolerates these extras or cast explicitly:

const rawUser = await createUser({...});
return rawUser as unknown as AdapterUser; // or pick the needed fields

Failing to align the types can surface subtle runtime issues when next-auth serialises the session.

@vercel vercel bot temporarily deployed to Preview – landing June 16, 2025 14:46 Inactive
@lukevella lukevella merged commit 424f39a into main Jun 16, 2025
11 checks passed
@lukevella lukevella deleted the space/members branch June 16, 2025 21:34
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