Files
hounam-submit-form-backend/src/modules/permission/service/permission.service.ts

76 lines
1.6 KiB
TypeScript

import { Permission } from "../../../models/Permission";
interface CreatePermissionDto {
name: string;
}
interface UpdatePermissionDto {
name?: string;
}
class PermissionService {
async create(data: CreatePermissionDto) {
const existingPermission = await Permission.findOne({
where: { name: data.name },
});
if (existingPermission) {
throw new Error("سطح دسترسی با این نام قبلاً ثبت شده است");
}
const permission = await Permission.create({
name: data.name,
});
return permission;
}
async getAll() {
return await Permission.findAll({
order: [["createdAt", "DESC"]],
});
}
async getById(id: string) {
const permission = await Permission.findByPk(id);
if (!permission) {
throw new Error("سطح دسترسی مورد نظر یافت نشد");
}
return permission;
}
async update(id: string, data: UpdatePermissionDto) {
const permission = await this.getById(id);
if (data.name && data.name !== permission.name) {
const existingPermission = await Permission.findOne({
where: { name: data.name },
});
if (existingPermission) {
throw new Error("سطح دسترسی با این نام قبلاً ثبت شده است");
}
}
await permission.update({
name: data.name ?? permission.name,
});
return permission;
}
async delete(id: string) {
const permission = await this.getById(id);
await permission.destroy();
return {
message: "سطح دسترسی با موفقیت حذف شد",
};
}
}
export default new PermissionService();