- 移除了不必要的 getAllUsers 控制器方法 -重命名 findUserList 为 getUserList,更符合方法的实际功能- 引入 UserDTO 类,用于用户数据传输和验证 - 优化了错误处理和日志记录 - 简化了代码结构,提高了可读性和可维护性
77 lines
1.9 KiB
JavaScript
77 lines
1.9 KiB
JavaScript
import userRepository from '../repositories/userRepository.js'
|
|
import logger from 'morgan'
|
|
import messages from '../config/messages.js'
|
|
import { comparePassword } from '../utils/hashUtils.js'
|
|
|
|
const userService = {
|
|
/**
|
|
* 用户登录
|
|
* @param {string} account - 用户账号
|
|
* @param {string} password - 用户密码
|
|
* @returns {Promise<Object>} - 登录成功返回用户信息
|
|
* @throws {Error} - 如果用户不存在或密码不正确
|
|
*/
|
|
async login(account, password) {
|
|
const user = await userRepository.selectUserByAccount(account)
|
|
|
|
// 用户不存在
|
|
if (!user) {
|
|
throw new Error(messages.user.not_found)
|
|
}
|
|
|
|
// 密码不匹配
|
|
const isMatch = comparePassword(password, user.password)
|
|
if (!isMatch) {
|
|
throw new Error(messages.user.passwordIncorrect)
|
|
}
|
|
|
|
return user
|
|
},
|
|
|
|
/**
|
|
*
|
|
* @param {string} account
|
|
* @returns {Promise<boolean>}
|
|
*/
|
|
async getUserExists(account) {
|
|
return userRepository.selectUserByAccountExist(account)
|
|
},
|
|
|
|
async getUserList(searchQuery) {
|
|
return userRepository.selectUserList(searchQuery)
|
|
},
|
|
|
|
/**
|
|
* 创建用户
|
|
* @param {Object} user - 用户对象
|
|
* @returns {Promise<Object>} - 创建成功的用户信息
|
|
* @throws {Error} - 如果用户已存在或事务失败
|
|
*/
|
|
async createUser(user) {
|
|
const session = await userRepository.startTransaction()
|
|
|
|
try {
|
|
const userExists = await userRepository.selectUserByAccountExists(user.account)
|
|
|
|
if (userExists) {
|
|
return new Error(messages.user.alreadyExists)
|
|
}
|
|
|
|
await userRepository.createUser(user)
|
|
|
|
await userRepository.commitTransaction(session)
|
|
} catch (err) {
|
|
logger(err)
|
|
try {
|
|
await userRepository.rollbackTransaction(session)
|
|
} catch (err) {
|
|
logger(err)
|
|
throw err
|
|
}
|
|
throw err
|
|
}
|
|
}
|
|
}
|
|
|
|
export default userService
|