/** * TeamMember model - links users to teams with roles */ import * as plugins from '../plugins.ts'; import type { ITeamMember, TTeamRole } from '../interfaces/auth.interfaces.ts'; import { getDb } from './db.ts'; @plugins.smartdata.Collection(() => getDb()) export class TeamMember extends plugins.smartdata.SmartDataDbDoc implements ITeamMember { @plugins.smartdata.unI() public id: string = ''; @plugins.smartdata.svDb() @plugins.smartdata.index() public teamId: string = ''; @plugins.smartdata.svDb() @plugins.smartdata.index() public userId: string = ''; @plugins.smartdata.svDb() @plugins.smartdata.index() public role: TTeamRole = 'member'; @plugins.smartdata.svDb() @plugins.smartdata.index() public createdAt: Date = new Date(); /** * Add a member to a team */ public static async addMember(data: { teamId: string; userId: string; role: TTeamRole; }): Promise { // Check if member already exists const existing = await TeamMember.getInstance({ teamId: data.teamId, userId: data.userId, }); if (existing) { throw new Error('User is already a member of this team'); } const member = new TeamMember(); member.id = await TeamMember.getNewId(); member.teamId = data.teamId; member.userId = data.userId; member.role = data.role; member.createdAt = new Date(); await member.save(); return member; } /** * Find membership for user in team */ public static async findMembership(teamId: string, userId: string): Promise { return await TeamMember.getInstance({ teamId, userId, }); } /** * Get all members of a team */ public static async getTeamMembers(teamId: string): Promise { return await TeamMember.getInstances({ teamId, }); } /** * Get all teams a user belongs to */ public static async getUserTeams(userId: string): Promise { return await TeamMember.getInstances({ userId, }); } /** * Lifecycle hook */ public async beforeSave(): Promise { if (!this.id) { this.id = await TeamMember.getNewId(); } } }