75 lines
2.7 KiB
TypeScript
75 lines
2.7 KiB
TypeScript
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
|
import { InjectRepository } from "@nestjs/typeorm";
|
|
import { In, Not, Repository } from "typeorm";
|
|
import { WorkspaceRepository } from "../repositories/workspace.repository";
|
|
import { TMWorkspace } from "../entities/workspace.entity";
|
|
import { CreateWorkspaceDto } from "../dto/workspace/create-workspace.dto";
|
|
import { UpdateWorkspaceDto } from "../dto/workspace/update-workspace.dto";
|
|
import { User } from "../../users/entities/user.entity";
|
|
import { WorkSpaceMessage } from "../../../common/enums/message.enum";
|
|
import { PermissionEnum } from "../../users/enums/permission.enum";
|
|
|
|
@Injectable()
|
|
export class WorkspaceService {
|
|
constructor(
|
|
private readonly workspaceRepository: WorkspaceRepository,
|
|
@InjectRepository(User)
|
|
private readonly userRepository: Repository<User>,
|
|
) {}
|
|
|
|
async findOneOrFail(id: string): Promise<TMWorkspace> {
|
|
const workspace = await this.workspaceRepository.findOneWorkSpace(id);
|
|
if (!workspace) throw new NotFoundException(WorkSpaceMessage.WORKSPACE_NOT_FOUND);
|
|
return workspace;
|
|
}
|
|
|
|
async create(dto: CreateWorkspaceDto): Promise<TMWorkspace> {
|
|
const { userIds, ...rest } = dto;
|
|
|
|
const existingWorkspace = await this.workspaceRepository.findOne({ where: { name: rest.name } });
|
|
if (existingWorkspace) {
|
|
throw new BadRequestException(WorkSpaceMessage.WORKSPACE_EXISTS);
|
|
}
|
|
|
|
const workspace = this.workspaceRepository.create(rest);
|
|
|
|
if (userIds?.length) {
|
|
workspace.users = await this.userRepository.findBy({ id: In(userIds) });
|
|
}
|
|
|
|
return this.workspaceRepository.save(workspace);
|
|
}
|
|
|
|
async update(id: string, dto: UpdateWorkspaceDto): Promise<TMWorkspace> {
|
|
const workspace = await this.findOneOrFail(id);
|
|
const { userIds, ...rest } = dto;
|
|
|
|
if (rest.name) {
|
|
const existingWorkSpaceWithTheSameName = await this.workspaceRepository.findOne({ where: { name: rest.name, id: Not(id) } });
|
|
if (existingWorkSpaceWithTheSameName) throw new BadRequestException(WorkSpaceMessage.WORKSPACE_SAME_NAME_EXISTS);
|
|
}
|
|
|
|
Object.assign(workspace, rest);
|
|
|
|
if (userIds) {
|
|
workspace.users = userIds.length ? await this.userRepository.findBy({ id: In(userIds) }) : [];
|
|
}
|
|
|
|
return this.workspaceRepository.save(workspace);
|
|
}
|
|
|
|
async remove(id: string): Promise<TMWorkspace> {
|
|
const workspace = await this.findOneOrFail(id);
|
|
await this.workspaceRepository.delete(id);
|
|
|
|
return workspace;
|
|
}
|
|
|
|
async findByUser(userId: string, permissions: PermissionEnum[]): Promise<TMWorkspace[]> {
|
|
if(permissions.includes(PermissionEnum.WORKSPACE_READ)) {
|
|
return await this.workspaceRepository.find();
|
|
}
|
|
return await this.workspaceRepository.findByUser(userId);
|
|
}
|
|
}
|