refactor(user): 重构用户模块代码
- 将 userController、userModel、userRepository 和 userService 文件中的代码进行重新组织和优化 - 使用 import 语句替代 require 引入模块 - 将函数定义从 es5 改为 es6 语法 - 优化了部分函数的实现,提高了代码可读性和维护性
This commit is contained in:
parent
4edd3c2a26
commit
e6adea5f52
@ -6,16 +6,17 @@ import messages from '../config/messages'
|
||||
import { HTTP_STATUS } from '../common/constant/httpStatus'
|
||||
import { SearchQuery } from '../models/search'
|
||||
|
||||
export async function getAllUsers(res) {
|
||||
export default 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')
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
export async function findUserList(req, res) {
|
||||
async findUserList(req, res) {
|
||||
try {
|
||||
const { page, size, sort } = req.query
|
||||
const search = new SearchQuery({ page: page, size: size, sort: sort })
|
||||
@ -26,9 +27,9 @@ export async function findUserList(req, res) {
|
||||
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
export const createUser = [
|
||||
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'),
|
||||
@ -61,9 +62,9 @@ export const createUser = [
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||
}
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
export const login = [
|
||||
login: [
|
||||
body('account').notEmpty().withMessage('Account is required'),
|
||||
body('password').notEmpty().withMessage('Password is required'),
|
||||
async (req, res, next) => {
|
||||
@ -97,9 +98,10 @@ export const login = [
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||
}
|
||||
}
|
||||
]
|
||||
],
|
||||
|
||||
export async function logout(req, res) {
|
||||
logout: [
|
||||
async (req, res) => {
|
||||
try {
|
||||
req.session.destroy()
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.OK, messages.user.logout)
|
||||
@ -107,9 +109,10 @@ export async function logout(req, res) {
|
||||
logger('Error logging out: ', err)
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
export async function getUserExists(req, res) {
|
||||
async getUserExists(req, res) {
|
||||
try {
|
||||
const { account } = req.query
|
||||
|
||||
@ -123,4 +126,5 @@ export async function getUserExists(req, res) {
|
||||
logger('Error checking user existence: ', err)
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
const mongoose = require('mongoose')
|
||||
const { hashPassword } = require('../utils/hashUtils')
|
||||
const Schema = mongoose.Schema
|
||||
import { Schema as _Schema, model } from 'mongoose'
|
||||
import { hashPassword } from '../utils/hashUtils'
|
||||
const Schema = _Schema
|
||||
|
||||
const UserSchema = new Schema({
|
||||
name: { type: String, required: true, maxlength: 100 },
|
||||
@ -29,4 +29,4 @@ UserSchema.pre('save', async function (next) {
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = mongoose.model('User', UserSchema)
|
||||
export default model('User', UserSchema)
|
||||
|
||||
@ -1,25 +1,36 @@
|
||||
const UserModel = require('../models/userModel')
|
||||
const { SearchResult } = require('../models/search')
|
||||
import {
|
||||
startSession,
|
||||
find,
|
||||
aggregate,
|
||||
findById,
|
||||
findOne,
|
||||
exists,
|
||||
create,
|
||||
findByIdAndUpdate,
|
||||
findByIdAndDelete,
|
||||
deleteMany
|
||||
} from '../models/userModel'
|
||||
import { SearchResult } from '../models/search'
|
||||
|
||||
exports.startTransaction = async () => {
|
||||
const session = await UserModel.startSession()
|
||||
export async function startTransaction() {
|
||||
const session = await startSession()
|
||||
session.startTransaction()
|
||||
return session
|
||||
}
|
||||
|
||||
exports.commitTransaction = async (session) => {
|
||||
export async function commitTransaction(session) {
|
||||
return session.commitTransaction()
|
||||
}
|
||||
|
||||
exports.rollbackTransaction = async (session) => {
|
||||
export async function rollbackTransaction(session) {
|
||||
return session.abortTransaction()
|
||||
}
|
||||
|
||||
exports.selectAllUser = async () => {
|
||||
return UserModel.find()
|
||||
export async function selectAllUser() {
|
||||
return find()
|
||||
}
|
||||
|
||||
exports.selectUserList = async (search = {}) => {
|
||||
export async function selectUserList(search = {}) {
|
||||
try {
|
||||
const { size = 20, page = 1, sort, filters } = search
|
||||
|
||||
@ -32,7 +43,7 @@ exports.selectUserList = async (search = {}) => {
|
||||
const matchFilters = filters ? { ...filters } : {}
|
||||
const sortObj = sort && typeof sort === 'object' ? sort : { _id: 1 } // 默认按 _id 升序排序
|
||||
|
||||
const result = await UserModel.aggregate([
|
||||
const result = await aggregate([
|
||||
// 应用过滤条件,确保filters存在时才传入
|
||||
{ $match: matchFilters },
|
||||
{
|
||||
@ -57,47 +68,47 @@ exports.selectUserList = async (search = {}) => {
|
||||
}
|
||||
}
|
||||
|
||||
exports.selectUserById = async (id) => {
|
||||
return UserModel.findById(id)
|
||||
export async function selectUserById(id) {
|
||||
return findById(id)
|
||||
}
|
||||
|
||||
exports.selectUserByAccount = async (account) => {
|
||||
return UserModel.findOne({ account: account })
|
||||
export async function selectUserByAccount(account) {
|
||||
return findOne({ account: account })
|
||||
}
|
||||
|
||||
exports.selectUserByEmail = async (email) => {
|
||||
return UserModel.findOne({ email: email })
|
||||
export async function selectUserByEmail(email) {
|
||||
return findOne({ email: email })
|
||||
}
|
||||
|
||||
exports.selectUserByUsername = async (username) => {
|
||||
return UserModel.findOne({ username: username })
|
||||
export async function selectUserByUsername(username) {
|
||||
return findOne({ username: username })
|
||||
}
|
||||
|
||||
exports.selectUserByPhone = async (phone) => {
|
||||
return UserModel.findOne({ phone: phone })
|
||||
export async function selectUserByPhone(phone) {
|
||||
return findOne({ phone: phone })
|
||||
}
|
||||
|
||||
exports.selectUserByAccountExist = async (account) => {
|
||||
const exist = await UserModel.exists({ account: account })
|
||||
export async function selectUserByAccountExist(account) {
|
||||
const exist = await exists({ account: account })
|
||||
return exist !== null
|
||||
}
|
||||
|
||||
exports.createUser = async (user) => {
|
||||
return UserModel.create(user)
|
||||
export async function createUser(user) {
|
||||
return create(user)
|
||||
}
|
||||
|
||||
exports.updateUserById = async (id, user) => {
|
||||
return UserModel.findByIdAndUpdate(id, user)
|
||||
export async function updateUserById(id, user) {
|
||||
return findByIdAndUpdate(id, user)
|
||||
}
|
||||
|
||||
exports.updateUserByLoginDate = async (id, loginDate) => {
|
||||
return UserModel.findByIdAndUpdate(id, { last_login_date: loginDate })
|
||||
export async function updateUserByLoginDate(id, loginDate) {
|
||||
return findByIdAndUpdate(id, { last_login_date: loginDate })
|
||||
}
|
||||
|
||||
exports.deleteUserById = async (id) => {
|
||||
return UserModel.findByIdAndDelete(id)
|
||||
export async function deleteUserById(id) {
|
||||
return findByIdAndDelete(id)
|
||||
}
|
||||
|
||||
exports.deleteAllUser = async () => {
|
||||
return UserModel.deleteMany()
|
||||
export async function deleteAllUser() {
|
||||
return deleteMany()
|
||||
}
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
// routes/userRoutes.js
|
||||
import express from 'express'
|
||||
|
||||
import userController from '../controllers/userController'
|
||||
const userController = import('../controllers/userController')
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
router.get('/', userController.getUserExist)
|
||||
router.get('/', getUserExists)
|
||||
|
||||
export default router
|
||||
|
||||
@ -3,14 +3,15 @@ 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} - 如果用户不存在或密码不正确
|
||||
*/
|
||||
export async function login(account, password) {
|
||||
async login(account, password) {
|
||||
const user = await userMapper.selectUserByAccount(account)
|
||||
|
||||
// 用户不存在
|
||||
@ -29,33 +30,33 @@ export async function login(account, password) {
|
||||
await userMapper.updateUserByLoginDate(user.id, user.lastLoginDate)
|
||||
|
||||
return user
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
/**
|
||||
*
|
||||
* @param {string} account
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export async function getUserExists(account) {
|
||||
async getUserExists(account) {
|
||||
return userMapper.selectUserByAccountExist(account)
|
||||
}
|
||||
},
|
||||
|
||||
// Removed the unnecessary try-catch block and simplified the function
|
||||
export async function getAllUser() {
|
||||
// Removed the unnecessary try-catch block and simplified the function
|
||||
async getAllUser() {
|
||||
return await userMapper.selectAllUser()
|
||||
}
|
||||
},
|
||||
|
||||
export async function getUserList(searchQuery) {
|
||||
async getUserList(searchQuery) {
|
||||
return userMapper.selectUserList(searchQuery)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
/**
|
||||
* 创建用户
|
||||
* @param {Object} user - 用户对象
|
||||
* @returns {Promise<Object>} - 创建成功的用户信息
|
||||
* @throws {Error} - 如果用户已存在或事务失败
|
||||
*/
|
||||
export async function createUser(user) {
|
||||
async createUser(user) {
|
||||
const { account } = user
|
||||
const session = await userMapper.startTransaction()
|
||||
|
||||
@ -79,4 +80,5 @@ export async function createUser(user) {
|
||||
})
|
||||
throw err // 将错误抛给调用方(Controller 层)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user