From 21e4c3ea8acf92a292e0f4d8a1ff47616e607256 Mon Sep 17 00:00:00 2001 From: LingandRX Date: Sun, 5 Jan 2025 19:41:03 +0800 Subject: [PATCH] =?UTF-8?q?refactor(user):=20=E9=87=8D=E6=9E=84=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E6=A8=A1=E5=9D=97=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除了不必要的 getAllUsers 控制器方法 -重命名 findUserList 为 getUserList,更符合方法的实际功能- 引入 UserDTO 类,用于用户数据传输和验证 - 优化了错误处理和日志记录 - 简化了代码结构,提高了可读性和可维护性 --- controllers/userController.js | 38 ++++++++++++++-------------------- dto/userDTO.js | 28 +++++++++++++++++++++++++ models/userModel.js | 1 - repositories/userRepository.js | 15 ++++++++++---- routes/userRouter.js | 3 +-- services/userService.js | 30 +++++++++++---------------- 6 files changed, 67 insertions(+), 48 deletions(-) create mode 100644 dto/userDTO.js diff --git a/controllers/userController.js b/controllers/userController.js index 415731b..d7ff18b 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -5,40 +5,32 @@ import FetchResult from '../common/web/fetchResult.js' import messages from '../config/messages.js' import { HTTP_STATUS } from '../common/constant/httpStatus.js' import { SearchQuery } from '../models/search.js' +import { UserDTO } from '../dto/userDTO.js' const UserController = { - async getAllUsers(res) { - try { - const users = await userService.getUserList() - return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', users) - } catch (err) { - return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') - } - }, - async findUserList(req, res) { + async getUserList(req, res) { try { const { page, size, sort } = req.query const search = new SearchQuery({ page: page, size: size, sort: sort }) const result = await userService.getUserList(search) return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', result) } catch (err) { - console.log(err) - + logger(err) return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } }, createUser: [ - body('account').isLength({ min: 3 }).withMessage('Account must be at least 3 characters long'), - body('account').isEmpty().withMessage('Account is required'), - body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'), - body('password').isEmpty().withMessage('Password is required'), + body('account').isLength({ min: 3 }).withMessage(UserDTO.validationMessages.account.minLength), + body('account').isEmpty().withMessage(UserDTO.validationMessages.account.empty), + body('password').isLength({ min: 6 }).withMessage(UserDTO.validationMessages.password.minLength), + body('password').isEmpty().withMessage(UserDTO.validationMessages.password.empty), async (req, res, next) => { - const errors = validationResult(req) - if (!errors.isEmpty()) { + const err = validationResult(req) + if (!err.isEmpty()) { return FetchResult.formatResult( res, HTTP_STATUS.BAD_REQUEST, - errors + err .array() .map((err) => err.msg) .join(', ') @@ -53,7 +45,7 @@ const UserController = { await userService.createUser(user) return FetchResult.formatResult(res, HTTP_STATUS.CREATED, messages.user.created) } catch (err) { - logger('Error creating user: ', err) + logger(err) if (err.message === messages.user.alreadyExists) { return FetchResult.formatResult(res, HTTP_STATUS.CONFLICT, messages.user.alreadyExists) } @@ -90,7 +82,7 @@ const UserController = { return FetchResult.formatResult(res, HTTP_STATUS.NOT_FOUND, messages.user.accountPasswordNotMatch) } - logger('Error logging in: ', err) + logger(err) return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } @@ -102,7 +94,7 @@ const UserController = { req.session.destroy() return FetchResult.formatResult(res, HTTP_STATUS.OK, messages.user.logout) } catch (err) { - logger('Error logging out: ', err) + logger(err) return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } } @@ -118,10 +110,10 @@ const UserController = { } return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, messages.user.exists) } catch (err) { - logger('Error checking user existence: ', err) + logger(err) return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } - }, + } } export default UserController diff --git a/dto/userDTO.js b/dto/userDTO.js new file mode 100644 index 0000000..e8134e3 --- /dev/null +++ b/dto/userDTO.js @@ -0,0 +1,28 @@ +export class UserDTO { + constructor(user) { + this.id = user._id + this.username = user.username + this.account = user.account + this.password = user.password + this.email = user.email + this.registerDate = user.registerDate + this.lastLoginDate = user.lastLoginDate + } + + static validationMessages = { + account: { + minLength: 'Account must be at least 3 characters long.', + maxLength: 'Account must be at most 20 characters long.', + empty: 'Account is required.' + }, + password: { + minLength: 'Password must be at least 6 characters long.', + empty: 'Password is required.' + }, + passwordEmpty: 'Password is required.', + username: 'Username is required and must be at least 3 characters long.', + email: 'Email is required and must be a valid email address.', + registerDate: 'Register date is required and must be a valid date.', + lastLoginDate: 'Last login date is required and must be a valid date.' + } +} diff --git a/models/userModel.js b/models/userModel.js index 65682f9..44b080a 100644 --- a/models/userModel.js +++ b/models/userModel.js @@ -29,7 +29,6 @@ UserSchema.pre('save', async function (next) { } }) -// 更新 lastLoginDate 在用户登录时 UserSchema.methods.updateLastLoginDate = function () { this.lastLoginDate = new Date() } diff --git a/repositories/userRepository.js b/repositories/userRepository.js index 02b3eef..c097b3c 100644 --- a/repositories/userRepository.js +++ b/repositories/userRepository.js @@ -1,5 +1,6 @@ import User from '../models/userModel.js' import { SearchResult } from '../models/search.js' +import logger from 'morgan' const userRepository = { async startTransaction() { @@ -49,9 +50,9 @@ const userRepository = { searchResult.list = data return searchResult - } catch (error) { - console.log(error) - throw error + } catch (err) { + logger(err) + throw err } }, async selectUserById(id) { @@ -69,7 +70,13 @@ const userRepository = { async selectUserByPhone(phone) { return User.findOne({ phone: phone }) }, - async selectUserByAccountExist(account) { + + /** + * 检查用户是否存在 + * @param account + * @returns {Promise} + */ + async selectUserByAccountExists(account) { const exist = await User.exists({ account: account }) return exist !== null }, diff --git a/routes/userRouter.js b/routes/userRouter.js index fef1151..9c12ca2 100644 --- a/routes/userRouter.js +++ b/routes/userRouter.js @@ -3,8 +3,7 @@ import userController from '../controllers/userController.js' const router = express.Router() -router.get('/', userController.getAllUsers) router.post('/', userController.createUser) -router.get('/list', userController.findUserList) +router.get('/list', userController.getUserList) export default router diff --git a/services/userService.js b/services/userService.js index 0ea4315..38a2c92 100644 --- a/services/userService.js +++ b/services/userService.js @@ -37,11 +37,6 @@ const userService = { return userRepository.selectUserByAccountExist(account) }, - // Removed the unnecessary try-catch block and simplified the function - async getAllUser() { - return await userRepository.selectAllUser() - }, - async getUserList(searchQuery) { return userRepository.selectUserList(searchQuery) }, @@ -53,28 +48,27 @@ const userService = { * @throws {Error} - 如果用户已存在或事务失败 */ async createUser(user) { - const { account } = user const session = await userRepository.startTransaction() try { - // 检查用户是否已存在 - const existingUser = await userRepository.selectUserByAccount(account) - if (existingUser) { + const userExists = await userRepository.selectUserByAccountExists(user.account) + + if (userExists) { return new Error(messages.user.alreadyExists) } - // 创建新用户 - const result = await userRepository.createUser(user) + await userRepository.createUser(user) - // 提交事务 await userRepository.commitTransaction(session) - return result } catch (err) { - // 回滚事务 - await userRepository.rollbackTransaction(session).catch((rollbackErr) => { - logger('Error rolling back transaction: ', rollbackErr) - }) - throw err // 将错误抛给调用方(Controller 层) + logger(err) + try { + await userRepository.rollbackTransaction(session) + } catch (err) { + logger(err) + throw err + } + throw err } } }