Files
nxxmdata/backend/models/Role.js
2025-09-22 19:09:45 +08:00

113 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Role 模型定义
* @file Role.js
* @description 定义角色模型,用于数据库操作
*/
const { DataTypes } = require('sequelize');
const BaseModel = require('./BaseModel');
const { sequelize } = require('../config/database-simple');
/**
* 角色模型
* @typedef {Object} Role
* @property {number} id - 角色唯一标识
* @property {string} name - 角色名称,唯一
* @property {string} description - 角色描述
* @property {Date} created_at - 创建时间
*/
class Role extends BaseModel {
/**
* 获取具有此角色的所有用户
* @returns {Promise<Array>} 用户列表
*/
async getUsers() {
return await this.getUsers();
}
/**
* 检查角色是否已分配给指定用户
* @param {Number} userId 用户ID
* @returns {Promise<Boolean>} 检查结果
*/
async isAssignedToUser(userId) {
const users = await this.getUsers({ where: { id: userId } });
return users.length > 0;
}
/**
* 为角色分配用户
* @param {Number|Array} userId 用户ID或用户ID数组
* @returns {Promise<Boolean>} 分配结果
*/
async assignToUser(userId) {
try {
if (Array.isArray(userId)) {
await this.addUsers(userId);
} else {
await this.addUser(userId);
}
return true;
} catch (error) {
console.error('分配用户失败:', error);
return false;
}
}
/**
* 从用户中移除此角色
* @param {Number|Array} userId 用户ID或用户ID数组
* @returns {Promise<Boolean>} 移除结果
*/
async removeFromUser(userId) {
try {
if (Array.isArray(userId)) {
await this.removeUsers(userId);
} else {
await this.removeUser(userId);
}
return true;
} catch (error) {
console.error('移除用户失败:', error);
return false;
}
}
}
// 初始化Role模型
Role.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING(50),
allowNull: false,
unique: true
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
status: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true,
comment: '角色状态true-启用false-禁用'
}
}, {
sequelize,
tableName: 'roles',
modelName: 'Role',
timestamps: true,
createdAt: 'created_at',
updatedAt: false
});
// 关联关系已在 models/index.js 中定义
/**
* 导出角色模型
* @exports Role
*/
module.exports = Role;