From fbbcf675d171d932f92630400f681a97e5743a77 Mon Sep 17 00:00:00 2001 From: LingandRX Date: Sun, 5 Jan 2025 18:44:46 +0800 Subject: [PATCH] =?UTF-8?q?refactor(user):=20=E9=87=8D=E6=9E=84=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E7=9B=B8=E5=85=B3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 优化了用户路由、控制器、仓库和服务的代码结构 - 改进了代码的可读性和可维护性 -移除了冗余的导入和导出语句 - 统一了异步函数的定义方式- 简化了错误处理逻辑 --- common/constant/httpStatus.js | 2 - config/mongodbConfig.js | 7 +- controllers/userController.js | 7 +- models/Search.js | 4 +- repositories/userRepository.js | 185 ++++++++++++++------------------- routes/accountRouter.js | 1 - services/userService.js | 4 - 7 files changed, 81 insertions(+), 129 deletions(-) diff --git a/common/constant/httpStatus.js b/common/constant/httpStatus.js index 5abb9eb..3fdc6cf 100644 --- a/common/constant/httpStatus.js +++ b/common/constant/httpStatus.js @@ -66,5 +66,3 @@ export const HTTP_STATUS = { /** @type {number} 网关超时 */ GATEWAY_TIMEOUT: 504 } - -export default { HTTP_STATUS } diff --git a/config/mongodbConfig.js b/config/mongodbConfig.js index 69bdf43..b33676a 100644 --- a/config/mongodbConfig.js +++ b/config/mongodbConfig.js @@ -1,10 +1,7 @@ import mongoose from 'mongoose' - import logger from 'morgan' -import { config } from 'dotenv' - -config() +import('dotenv').config() // 使用环境变量存储敏感信息 const account = process.env.MONGO_ACCOUNT @@ -16,7 +13,7 @@ let isConnected = false export async function connectMongoDB() { if (process.env.NODE_ENV === 'development') { - logger(account, password, host, port) + logger({ account, password, host, port }) } // 如果已经连接,不再重复连接 diff --git a/controllers/userController.js b/controllers/userController.js index 94672fb..415731b 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -15,7 +15,6 @@ const UserController = { return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } }, - async findUserList(req, res) { try { const { page, size, sort } = req.query @@ -28,7 +27,6 @@ const UserController = { 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'), @@ -63,7 +61,6 @@ const UserController = { } } ], - login: [ body('account').notEmpty().withMessage('Account is required'), body('password').notEmpty().withMessage('Password is required'), @@ -99,7 +96,6 @@ const UserController = { } } ], - logout: [ async (req, res) => { try { @@ -111,7 +107,6 @@ const UserController = { } } ], - async getUserExists(req, res) { try { const { account } = req.query @@ -126,7 +121,7 @@ const UserController = { logger('Error checking user existence: ', err) return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } - } + }, } export default UserController diff --git a/models/Search.js b/models/Search.js index e9ffe57..d04ff7c 100644 --- a/models/Search.js +++ b/models/Search.js @@ -7,7 +7,7 @@ export class SearchQuery { } } -class SearchResult { +export class SearchResult { constructor({ list = [], num = 0, size = 0, total = 0 } = {}) { if (typeof num !== 'number') { throw new Error('Invalid num parameter') @@ -25,5 +25,3 @@ class SearchResult { this.total = total } } - -export default { SearchQuery, SearchResult } diff --git a/repositories/userRepository.js b/repositories/userRepository.js index 29724cf..02b3eef 100644 --- a/repositories/userRepository.js +++ b/repositories/userRepository.js @@ -2,123 +2,92 @@ import User from '../models/userModel.js' import { SearchResult } from '../models/search.js' const userRepository = { - startTransaction, - commitTransaction, - rollbackTransaction, - selectAllUser, - selectUserList, - selectUserById, - selectUserByAccount, - selectUserByEmail, - selectUserByUsername, - selectUserByPhone, - selectUserByAccountExist, - createUser, - updateUserById, - updateUserByLoginDate, - deleteUserById, - deleteAllUser -} + async startTransaction() { + const session = await User.startSession() + session.startTransaction() + return session + }, + async commitTransaction(session) { + return session.commitTransaction() + }, + async rollbackTransaction(session) { + return session.abortTransaction() + }, + async selectAllUser() { + return User.find() + }, + async selectUserList(search = {}) { + try { + const { size = 20, page = 1, sort, filters } = search -export async function startTransaction() { - const session = await User.startSession() - session.startTransaction() - return session -} + const skip = (page - 1) * size + const searchResult = new SearchResult() + searchResult.num = page + searchResult.size = size -export async function commitTransaction(session) { - return session.commitTransaction() -} + // 检查 filters,确保只有在 filters 存在时才应用 + const matchFilters = filters ? { ...filters } : {} -export async function rollbackTransaction(session) { - return session.abortTransaction() -} + const sortObj = sort && typeof sort === 'object' ? sort : { _id: 1 } -export async function selectAllUser() { - return User.find() -} - -export async function selectUserList(search = {}) { - try { - const { size = 20, page = 1, sort, filters } = search - - const skip = (page - 1) * size - const searchResult = new SearchResult() - searchResult.num = page - searchResult.size = size - - // 检查 filters,确保只有在 filters 存在时才应用 - const matchFilters = filters ? { ...filters } : {} - const sortObj = sort && typeof sort === 'object' ? sort : { _id: 1 } // 默认按 _id 升序排序 - - const result = await User.aggregate([ - // 应用过滤条件,确保filters存在时才传入 - { $match: matchFilters }, - { - $facet: { - metadata: [{ $count: 'total' }, { $addFields: { total: '$total' } }], - data: [{ $sort: sortObj }, { $skip: skip }, { $limit: size }] + const result = await User.aggregate([ + // 应用过滤条件,确保filters存在时才传入 + { $match: matchFilters }, + { + $facet: { + metadata: [{ $count: 'total' }, { $addFields: { total: '$total' } }], + data: [{ $sort: sortObj }, { $skip: skip }, { $limit: size }] + } } - } - ]) + ]) - // 解构 result 并进行必要的空值检查 - const { metadata = [], data = [] } = result[0] || {} + // 解构 result 并进行必要的空值检查 + const { metadata = [], data = [] } = result[0] || {} - // 提取 metadata 中的 total,若不存在则为 0 - searchResult.total = metadata.length > 0 ? metadata[0].total : 0 - searchResult.list = data + // 提取 metadata 中的 total,若不存在则为 0 + searchResult.total = metadata.length > 0 ? metadata[0].total : 0 + searchResult.list = data - return searchResult - } catch (error) { - console.log(error) - throw error + return searchResult + } catch (error) { + console.log(error) + throw error + } + }, + async selectUserById(id) { + return User.findById(id) + }, + async selectUserByAccount(account) { + return User.findOne({ account: account }) + }, + async selectUserByEmail(email) { + return User.findOne({ email: email }) + }, + async selectUserByUsername(username) { + return User.findOne({ username: username }) + }, + async selectUserByPhone(phone) { + return User.findOne({ phone: phone }) + }, + async selectUserByAccountExist(account) { + const exist = await User.exists({ account: account }) + return exist !== null + }, + async createUser(user) { + return User.create(user) + }, + async updateUserById(id, user) { + return User.findByIdAndUpdate(id, user) + }, + async updateUserByLoginDate(id, loginDate) { + return User.findByIdAndUpdate(id, { lastLoginDate: loginDate }) + }, + async deleteUserById(id) { + return User.findByIdAndDelete(id) + }, + async deleteAllUser() { + return User.deleteMany() } } -export async function selectUserById(id) { - return User.findById(id) -} - -export async function selectUserByAccount(account) { - return User.findOne({ account: account }) -} - -export async function selectUserByEmail(email) { - return User.findOne({ email: email }) -} - -export async function selectUserByUsername(username) { - return User.findOne({ username: username }) -} - -export async function selectUserByPhone(phone) { - return User.findOne({ phone: phone }) -} - -export async function selectUserByAccountExist(account) { - const exist = await User.exists({ account: account }) - return exist !== null -} - -export async function createUser(user) { - return User.create(user) -} - -export async function updateUserById(id, user) { - return User.findByIdAndUpdate(id, user) -} - -export async function updateUserByLoginDate(id, loginDate) { - return User.findByIdAndUpdate(id, { lastLoginDate: loginDate }) -} - -export async function deleteUserById(id) { - return User.findByIdAndDelete(id) -} - -export async function deleteAllUser() { - return User.deleteMany() -} - export default userRepository diff --git a/routes/accountRouter.js b/routes/accountRouter.js index 5e0c7f5..8df10a1 100644 --- a/routes/accountRouter.js +++ b/routes/accountRouter.js @@ -1,4 +1,3 @@ -// routes/userRoutes.js import express from 'express' import userController from '../controllers/userController.js' diff --git a/services/userService.js b/services/userService.js index 61d423c..0ea4315 100644 --- a/services/userService.js +++ b/services/userService.js @@ -25,10 +25,6 @@ const userService = { throw new Error(messages.user.passwordIncorrect) } - // 更新用户的最后登录时间 - user.lastLoginDate = new Date() - await userRepository.updateUserByLoginDate(user.id, user.lastLoginDate) - return user },