Files
registry/ts/models/team.member.ts

95 lines
2.2 KiB
TypeScript

/**
* TeamMember model - links users to teams with roles
*/
import * as plugins from '../plugins.ts';
import type { ITeamMember, TTeamRole } from '../interfaces/auth.interfaces.ts';
import { db } from './db.ts';
@plugins.smartdata.Collection(() => db)
export class TeamMember extends plugins.smartdata.SmartDataDbDoc<TeamMember, TeamMember> 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<TeamMember> {
// 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<TeamMember | null> {
return await TeamMember.getInstance({
teamId,
userId,
});
}
/**
* Get all members of a team
*/
public static async getTeamMembers(teamId: string): Promise<TeamMember[]> {
return await TeamMember.getInstances({
teamId,
});
}
/**
* Get all teams a user belongs to
*/
public static async getUserTeams(userId: string): Promise<TeamMember[]> {
return await TeamMember.getInstances({
userId,
});
}
/**
* Lifecycle hook
*/
public async beforeSave(): Promise<void> {
if (!this.id) {
this.id = await TeamMember.getNewId();
}
}
}