From 3cd150b1067d70dcdfbea6c69bc35653546720b9 Mon Sep 17 00:00:00 2001 From: LingandRX <56020800+LingandRX@users.noreply.github.com> Date: Tue, 31 Dec 2024 00:17:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(user):=20=E6=B7=BB=E5=8A=A0=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E5=88=97=E8=A1=A8=E6=9F=A5=E8=AF=A2=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 findUserList 控制器方法,用于查询用户列表 - 创建 Search 模型类,用于处理查询参数 - 在用户仓库中实现 selectUserList 方法,用于数据库查询 - 更新用户服务,添加 find_user_list 方法 - 在路由中注册新的用户列表查询 endpoint --- controllers/userController.js | 16 +++++++++++++- models/Search.js | 32 ++++++++++++++++++++++++++++ repositories/userRepository.js | 39 ++++++++++++++++++++++++++++++++++ routes/userRouter.js | 1 + services/userService.js | 8 +++++++ utils/loginUtil.js | 1 + 6 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 models/Search.js diff --git a/controllers/userController.js b/controllers/userController.js index 2b2f80b..9d2d21e 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -3,16 +3,30 @@ const userService = require('../services/userService') const FetchResult = require('../common/web/fetchResult') const messages = require('../config/messages') const { HTTP_STATUS } = require('../common/constant/httpStatus') +const { Search } = require('../models/Search') exports.getAllUsers = async (res) => { try { const users = await userService.user_list() - return FetchResult.formatResult(res, 200, 'success', users) + return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', users) } catch (err) { return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } } +exports.findUserList = async (req, res) => { + try { + const { page, size, sort } = req.query + const search = new Search({ page: page, size: size, sort: sort }) + const result = await userService.find_user_list(search) + return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', result) + } catch (err) { + console.log(err) + + return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') + } +} + exports.createUser = [ body('account').isLength({ min: 3 }).withMessage('Account must be at least 3 characters long'), body('account').isEmpty().withMessage('Account is required'), diff --git a/models/Search.js b/models/Search.js new file mode 100644 index 0000000..3e29be6 --- /dev/null +++ b/models/Search.js @@ -0,0 +1,32 @@ +class Search { + constructor({ size, page, sort, filters }) { + this.size = size + this.page = page + this.sort = sort + this.filters = filters + } +} + +class SearchResult { + constructor({ list = [], num = 0, size = 0, total = 0 } = {}) { + if (typeof list !== 'object' || list === null) { + throw new Error('Invalid list parameter') + } + if (typeof num !== 'number') { + throw new Error('Invalid num parameter') + } + if (typeof size !== 'number') { + throw new Error('Invalid size parameter') + } + if (typeof total !== 'number') { + throw new Error('Invalid total parameter') + } + + this.list = list + this.num = num + this.size = size + this.total = total + } +} + +module.exports = { Search, SearchResult } diff --git a/repositories/userRepository.js b/repositories/userRepository.js index b8376d7..67cbfa5 100644 --- a/repositories/userRepository.js +++ b/repositories/userRepository.js @@ -1,4 +1,5 @@ const UserModel = require('../models/userModel') +const { SearchResult } = require('../models/Search') exports.startTransaction = async () => { const seesion = await UserModel.startSession() @@ -18,6 +19,44 @@ exports.selectAllUser = async () => { return await UserModel.find() } +exports.selectUserList = async (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 UserModel.aggregate([ + // 应用过滤条件,确保filters存在时才传入 + { $match: matchFilters }, + { + $facet: { + metadata: [{ $count: 'total' }, { $addFields: { total: '$total' } }], + data: [{ $sort: sortObj }, { $skip: skip }, { $limit: size }] + } + } + ]) + + // 解构 result 并进行必要的空值检查 + const { metadata = [], data = [] } = result[0] || {} + + // 提取 metadata 中的 total,若不存在则为 0 + searchResult.total = metadata.length > 0 ? metadata[0].total : 0 + searchResult.list = data + + return searchResult + } catch (error) { + console.log(error) + throw error + } +} + exports.selectUserById = async (id) => { return await UserModel.findById(id) } diff --git a/routes/userRouter.js b/routes/userRouter.js index 8ae1740..12aafb0 100644 --- a/routes/userRouter.js +++ b/routes/userRouter.js @@ -6,5 +6,6 @@ const router = express.Router() router.get('/', userController.getAllUsers) router.post('/', userController.createUser) +router.get('/list', userController.findUserList) module.exports = router diff --git a/services/userService.js b/services/userService.js index d31b642..17cebae 100644 --- a/services/userService.js +++ b/services/userService.js @@ -55,6 +55,14 @@ exports.user_list = async () => { } } +exports.find_user_list = async (search) => { + try { + return await userMapper.selectUserList(search) + } catch (err) { + throw err + } +} + exports.create_user = async (user) => { try { const { account } = user diff --git a/utils/loginUtil.js b/utils/loginUtil.js index 46a2d4e..588d112 100644 --- a/utils/loginUtil.js +++ b/utils/loginUtil.js @@ -1,4 +1,5 @@ const FetchResult = require('../common/web/fetchResult.js') +const { HTTP_STATUS } = require('../common/constant/httpStatus.js') exports.authenticateSession = async (req, res, next) => { if (req.session.user) {