Skip to Content
gentlemans-stack
ReferenceDomains

workspace-domain

Mongoose persistence boundary for workspace and its invitations (one package, so invite accept can write both collections in one transaction).

API

FileExports
workspace.schema.tsgetWorkspaceModel(connection), WorkspaceDocument, WorkspaceMongooseModel
audit-hook.tsMemberAuditHook
workspace.repository.tscreateWorkspaceDomainRepository(connection, logger), WorkspaceDomainRepository
invitation.schema.tsgetInvitationModel(connection), InvitationDocument, InvitationMongooseModel
invitation.repository.tscreateInvitationDomainRepository(connection, logger), InvitationDomainRepository, AcceptInvitationResult

A workspace embeds its members: { members: [{ role, userId }], name }, one entry per user, with a multikey index on members.userId for "my workspaces". The model is idempotent: it reuses connection.models.Workspace if registered.

Methods

MethodWhat it does
create({ name, ownerId })New workspace with the creator as its only owner.
listForUser(userId)The workspaces the user is a member of, oldest first (uses the members index).
findById(id)The workspace, or undefined.
findMemberRole({ userId, workspaceId })The user's role, or undefined for a non-member or unknown workspace. This is what the intent guard calls.
rename({ id, name }), delete(id)Throw RESOURCE_NOT_FOUND when the workspace does not exist.
setMemberRole({ audit?, role, userId, workspaceId })role is never owner. Returns { status }: updated, last_owner, member_not_found or not_found.
removeMember({ audit?, userId, workspaceId })Same result type as setMemberRole.
transferOwnership({ fromUserId, toUserId, workspaceId })Target becomes owner and the caller an admin in one update. Returns updated, not_owner, member_not_found or not_found.

The last-owner rule is atomic: setMemberRole and removeMember put "another owner exists (or this member is not an owner)" into the update filter, so two owners demoting each other at once cannot leave the workspace without one.

Audit hook

setMemberRole, removeMember and acceptInvitation take an optional audit: MemberAuditHook, ({ after?, before?, invitationId?, session, workspaceId? }) => Promise<unknown> (invitationId and workspaceId only for acceptInvitation), so a caller can write an audit row that commits or aborts with the change. Without it nothing changes: one plain update, no transaction. With it the method runs in createRunInTransaction (a replica set is required): the previous role is read in the session, the guarded update runs in it, and only an applied change calls the hook, with before: { role } (role change, removal) and after: { role } (role change; the joined role on accept). A refused change (last_owner, member_not_found, not_found, any accept refusal) never calls it. A throw from the hook rolls the change back (an accepted invite stays unused) and propagates. MongoDB may retry the transaction, running the hook again, so it must write only through session.

Invitations

Collection workspaceInvitations: { email, expiresAt, invitedBy, revokedAt, role, tokenHash, usedAt, usedBy, workspaceId } with timestamps. email is stored lowercased; tokenHash is the SHA-256 (hex) of the invite token and is unique; the plaintext token is never stored. There is no TTL index, so an expired invite is still found and reported as expired.

MethodWhat it does
create({ email, expiresAt, invitedBy, role, tokenHash, workspaceId })Stores a new invite (email lowercased) and returns the public Invitation, which never carries the hash.
listPending({ now, workspaceId })That workspace's invites that are unused, unrevoked and not expired at now, oldest first.
deleteForWorkspace(workspaceId)Deletes every invite of a deleted workspace and returns the count.
revoke({ id, now, workspaceId })Sets revokedAt on an unused, unrevoked invite of that workspace and returns it; undefined for an unknown id, another workspace's invite, or one already used or revoked.
acceptInvitation({ email, now, tokenHash, userId })Returns { status: "accepted", workspaceId } or a refusal status: not_found, invite_used (used or revoked), invite_expired (at or after expiresAt), email_mismatch (compared lowercased; a missing email never matches), already_member, workspace_not_found.

acceptInvitation runs in one createRunInTransaction (@gentlemans-stack/mongodb-connector/transaction), so it needs a replica set. It marks the invite used with a filter on usedAt: null, revokedAt: null and expiresAt > now, then pushes { role, userId } into the workspace with a filter that the user is not already a member. When that push matches nothing, it throws inside the transaction, so the used mark rolls back and the invite stays usable. A concurrent accept or revoke of the same invite makes MongoDB retry the transaction, which then sees it used: exactly one accept wins.

Complete the domain

  1. Generate a portable model in models/workspace-model when multiple layers share the resource representation.
  2. Derive the persistence type from that portable model, replacing only serialized IDs/dates with native types, then map its fields, defaults, indexes, and references in workspace.schema.ts.
  3. Add repository methods and integration tests using the suite in workspace.repository.spec.ts.
  4. Wire a consuming service only when it actually uses this domain: add the workspace dependency and TypeScript reference, then construct the repository in its composition root.

Tests

The source-adjacent Vitest suites each use a dedicated Mongoose connection, clear collections after each test, and close the connection before stopping the server. workspace.repository.spec.ts starts a MongoMemoryServer; invitation.repository.spec.ts starts a one-node MongoMemoryReplSet, because accept runs in a transaction.

Commands

pnpm nx run workspace-domain:typecheck   # type-check the package
pnpm nx run workspace-domain:test        # run the Vitest suite

On this page