You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
107 lines
2.5 KiB
107 lines
2.5 KiB
import BaseModel from "@/base/BaseModel.js"
|
|
|
|
class UserModel extends BaseModel {
|
|
/**
|
|
* @returns {UserModel}
|
|
*/
|
|
static getInstance() {
|
|
return super.getInstance()
|
|
}
|
|
|
|
constructor() {
|
|
super()
|
|
}
|
|
|
|
get tableName() {
|
|
return "users"
|
|
}
|
|
|
|
get searchableFields() {
|
|
return ["username", "email", "name"]
|
|
}
|
|
|
|
get filterableFields() {
|
|
return ["role", "status"]
|
|
}
|
|
|
|
// 特定业务方法
|
|
async findByUsername(username) {
|
|
return this.findFirst({ username })
|
|
}
|
|
|
|
async findByEmail(email) {
|
|
return this.findFirst({ email })
|
|
}
|
|
|
|
// 重写create方法添加验证
|
|
async create(data) {
|
|
// 验证唯一性
|
|
if (data.username) {
|
|
const existingUser = await this.findByUsername(data.username)
|
|
if (existingUser) {
|
|
throw new Error("用户名已存在")
|
|
}
|
|
}
|
|
|
|
if (data.email) {
|
|
const existingEmail = await this.findByEmail(data.email)
|
|
if (existingEmail) {
|
|
throw new Error("邮箱已存在")
|
|
}
|
|
}
|
|
|
|
return super.create(data)
|
|
}
|
|
|
|
// 重写update方法添加验证
|
|
async update(id, data) {
|
|
console.log(id, data);
|
|
|
|
// 验证唯一性(排除当前用户)
|
|
if (data.username) {
|
|
const existingUser = await this.findFirst({ username: data.username })
|
|
if (existingUser && existingUser.id !== parseInt(id)) {
|
|
throw new Error("用户名已存在")
|
|
}
|
|
}
|
|
|
|
if (data.email) {
|
|
const existingEmail = await this.findFirst({ email: data.email })
|
|
if (existingEmail && existingEmail.id !== parseInt(id)) {
|
|
throw new Error("邮箱已存在")
|
|
}
|
|
}
|
|
|
|
return super.update(id, data)
|
|
}
|
|
|
|
// 用户状态管理
|
|
async activate(id) {
|
|
return this.update(id, { status: "active" })
|
|
}
|
|
|
|
async deactivate(id) {
|
|
return this.update(id, { status: "inactive" })
|
|
}
|
|
|
|
// 按角色查找用户
|
|
async findByRole(role) {
|
|
return this.findWhere({ role })
|
|
}
|
|
|
|
// 获取用户统计
|
|
async getUserStats() {
|
|
const total = await this.count()
|
|
const active = await this.count({ status: "active" })
|
|
const inactive = await this.count({ status: "inactive" })
|
|
|
|
return {
|
|
total,
|
|
active,
|
|
inactive,
|
|
}
|
|
}
|
|
}
|
|
|
|
export default UserModel
|
|
export { UserModel }
|
|
|