expressServer/services/userService.js
LingandRX e6adea5f52 refactor(user): 重构用户模块代码
- 将 userController、userModel、userRepository 和 userService 文件中的代码进行重新组织和优化
- 使用 import 语句替代 require 引入模块
- 将函数定义从 es5 改为 es6 语法
- 优化了部分函数的实现,提高了代码可读性和维护性
2025-01-05 00:13:10 +08:00

85 lines
2.3 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.

import userMapper from '../repositories/userRepository'
import logger from 'morgan'
import messages from '../config/messages'
import { comparePassword } from '../utils/hashUtils'
export default userServeice = {
/**
* 用户登录
* @param {string} account - 用户账号
* @param {string} password - 用户密码
* @returns {Promise<Object>} - 登录成功返回用户信息
* @throws {Error} - 如果用户不存在或密码不正确
*/
async login(account, password) {
const user = await userMapper.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)
}
// 更新用户的最后登录时间
user.lastLoginDate = new Date()
await userMapper.updateUserByLoginDate(user.id, user.lastLoginDate)
return user
},
/**
*
* @param {string} account
* @returns {Promise<boolean>}
*/
async getUserExists(account) {
return userMapper.selectUserByAccountExist(account)
},
// Removed the unnecessary try-catch block and simplified the function
async getAllUser() {
return await userMapper.selectAllUser()
},
async getUserList(searchQuery) {
return userMapper.selectUserList(searchQuery)
},
/**
* 创建用户
* @param {Object} user - 用户对象
* @returns {Promise<Object>} - 创建成功的用户信息
* @throws {Error} - 如果用户已存在或事务失败
*/
async createUser(user) {
const { account } = user
const session = await userMapper.startTransaction()
try {
// 检查用户是否已存在
const existingUser = await userMapper.selectUserByAccount(account)
if (existingUser) {
return new Error(messages.user.alreadyExists)
}
// 创建新用户
const result = await userMapper.createUser(user)
// 提交事务
await userMapper.commitTransaction(session)
return result
} catch (err) {
// 回滚事务
await userMapper.rollbackTransaction(session).catch((rollbackErr) => {
logger('Error rolling back transaction: ', rollbackErr)
})
throw err // 将错误抛给调用方Controller 层)
}
}
}