refactor(user): 重构用户相关代码
- 优化了用户路由、控制器、仓库和服务的代码结构 - 改进了代码的可读性和可维护性 -移除了冗余的导入和导出语句 - 统一了异步函数的定义方式- 简化了错误处理逻辑
This commit is contained in:
parent
039317d229
commit
fbbcf675d1
@ -66,5 +66,3 @@ export const HTTP_STATUS = {
|
|||||||
/** @type {number} 网关超时 */
|
/** @type {number} 网关超时 */
|
||||||
GATEWAY_TIMEOUT: 504
|
GATEWAY_TIMEOUT: 504
|
||||||
}
|
}
|
||||||
|
|
||||||
export default { HTTP_STATUS }
|
|
||||||
|
|||||||
@ -1,10 +1,7 @@
|
|||||||
import mongoose from 'mongoose'
|
import mongoose from 'mongoose'
|
||||||
|
|
||||||
import logger from 'morgan'
|
import logger from 'morgan'
|
||||||
|
|
||||||
import { config } from 'dotenv'
|
import('dotenv').config()
|
||||||
|
|
||||||
config()
|
|
||||||
|
|
||||||
// 使用环境变量存储敏感信息
|
// 使用环境变量存储敏感信息
|
||||||
const account = process.env.MONGO_ACCOUNT
|
const account = process.env.MONGO_ACCOUNT
|
||||||
@ -16,7 +13,7 @@ let isConnected = false
|
|||||||
|
|
||||||
export async function connectMongoDB() {
|
export async function connectMongoDB() {
|
||||||
if (process.env.NODE_ENV === 'development') {
|
if (process.env.NODE_ENV === 'development') {
|
||||||
logger(account, password, host, port)
|
logger({ account, password, host, port })
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果已经连接,不再重复连接
|
// 如果已经连接,不再重复连接
|
||||||
|
|||||||
@ -15,7 +15,6 @@ const UserController = {
|
|||||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async findUserList(req, res) {
|
async findUserList(req, res) {
|
||||||
try {
|
try {
|
||||||
const { page, size, sort } = req.query
|
const { page, size, sort } = req.query
|
||||||
@ -28,7 +27,6 @@ const UserController = {
|
|||||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
createUser: [
|
createUser: [
|
||||||
body('account').isLength({ min: 3 }).withMessage('Account must be at least 3 characters long'),
|
body('account').isLength({ min: 3 }).withMessage('Account must be at least 3 characters long'),
|
||||||
body('account').isEmpty().withMessage('Account is required'),
|
body('account').isEmpty().withMessage('Account is required'),
|
||||||
@ -63,7 +61,6 @@ const UserController = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|
||||||
login: [
|
login: [
|
||||||
body('account').notEmpty().withMessage('Account is required'),
|
body('account').notEmpty().withMessage('Account is required'),
|
||||||
body('password').notEmpty().withMessage('Password is required'),
|
body('password').notEmpty().withMessage('Password is required'),
|
||||||
@ -99,7 +96,6 @@ const UserController = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|
||||||
logout: [
|
logout: [
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@ -111,7 +107,6 @@ const UserController = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|
||||||
async getUserExists(req, res) {
|
async getUserExists(req, res) {
|
||||||
try {
|
try {
|
||||||
const { account } = req.query
|
const { account } = req.query
|
||||||
@ -126,7 +121,7 @@ const UserController = {
|
|||||||
logger('Error checking user existence: ', err)
|
logger('Error checking user existence: ', err)
|
||||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
export default UserController
|
export default UserController
|
||||||
|
|||||||
@ -7,7 +7,7 @@ export class SearchQuery {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class SearchResult {
|
export class SearchResult {
|
||||||
constructor({ list = [], num = 0, size = 0, total = 0 } = {}) {
|
constructor({ list = [], num = 0, size = 0, total = 0 } = {}) {
|
||||||
if (typeof num !== 'number') {
|
if (typeof num !== 'number') {
|
||||||
throw new Error('Invalid num parameter')
|
throw new Error('Invalid num parameter')
|
||||||
@ -25,5 +25,3 @@ class SearchResult {
|
|||||||
this.total = total
|
this.total = total
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default { SearchQuery, SearchResult }
|
|
||||||
|
|||||||
@ -2,43 +2,21 @@ import User from '../models/userModel.js'
|
|||||||
import { SearchResult } from '../models/search.js'
|
import { SearchResult } from '../models/search.js'
|
||||||
|
|
||||||
const userRepository = {
|
const userRepository = {
|
||||||
startTransaction,
|
async startTransaction() {
|
||||||
commitTransaction,
|
|
||||||
rollbackTransaction,
|
|
||||||
selectAllUser,
|
|
||||||
selectUserList,
|
|
||||||
selectUserById,
|
|
||||||
selectUserByAccount,
|
|
||||||
selectUserByEmail,
|
|
||||||
selectUserByUsername,
|
|
||||||
selectUserByPhone,
|
|
||||||
selectUserByAccountExist,
|
|
||||||
createUser,
|
|
||||||
updateUserById,
|
|
||||||
updateUserByLoginDate,
|
|
||||||
deleteUserById,
|
|
||||||
deleteAllUser
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function startTransaction() {
|
|
||||||
const session = await User.startSession()
|
const session = await User.startSession()
|
||||||
session.startTransaction()
|
session.startTransaction()
|
||||||
return session
|
return session
|
||||||
}
|
},
|
||||||
|
async commitTransaction(session) {
|
||||||
export async function commitTransaction(session) {
|
|
||||||
return session.commitTransaction()
|
return session.commitTransaction()
|
||||||
}
|
},
|
||||||
|
async rollbackTransaction(session) {
|
||||||
export async function rollbackTransaction(session) {
|
|
||||||
return session.abortTransaction()
|
return session.abortTransaction()
|
||||||
}
|
},
|
||||||
|
async selectAllUser() {
|
||||||
export async function selectAllUser() {
|
|
||||||
return User.find()
|
return User.find()
|
||||||
}
|
},
|
||||||
|
async selectUserList(search = {}) {
|
||||||
export async function selectUserList(search = {}) {
|
|
||||||
try {
|
try {
|
||||||
const { size = 20, page = 1, sort, filters } = search
|
const { size = 20, page = 1, sort, filters } = search
|
||||||
|
|
||||||
@ -49,7 +27,8 @@ export async function selectUserList(search = {}) {
|
|||||||
|
|
||||||
// 检查 filters,确保只有在 filters 存在时才应用
|
// 检查 filters,确保只有在 filters 存在时才应用
|
||||||
const matchFilters = filters ? { ...filters } : {}
|
const matchFilters = filters ? { ...filters } : {}
|
||||||
const sortObj = sort && typeof sort === 'object' ? sort : { _id: 1 } // 默认按 _id 升序排序
|
|
||||||
|
const sortObj = sort && typeof sort === 'object' ? sort : { _id: 1 }
|
||||||
|
|
||||||
const result = await User.aggregate([
|
const result = await User.aggregate([
|
||||||
// 应用过滤条件,确保filters存在时才传入
|
// 应用过滤条件,确保filters存在时才传入
|
||||||
@ -74,51 +53,41 @@ export async function selectUserList(search = {}) {
|
|||||||
console.log(error)
|
console.log(error)
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
async selectUserById(id) {
|
||||||
export async function selectUserById(id) {
|
|
||||||
return User.findById(id)
|
return User.findById(id)
|
||||||
}
|
},
|
||||||
|
async selectUserByAccount(account) {
|
||||||
export async function selectUserByAccount(account) {
|
|
||||||
return User.findOne({ account: account })
|
return User.findOne({ account: account })
|
||||||
}
|
},
|
||||||
|
async selectUserByEmail(email) {
|
||||||
export async function selectUserByEmail(email) {
|
|
||||||
return User.findOne({ email: email })
|
return User.findOne({ email: email })
|
||||||
}
|
},
|
||||||
|
async selectUserByUsername(username) {
|
||||||
export async function selectUserByUsername(username) {
|
|
||||||
return User.findOne({ username: username })
|
return User.findOne({ username: username })
|
||||||
}
|
},
|
||||||
|
async selectUserByPhone(phone) {
|
||||||
export async function selectUserByPhone(phone) {
|
|
||||||
return User.findOne({ phone: phone })
|
return User.findOne({ phone: phone })
|
||||||
}
|
},
|
||||||
|
async selectUserByAccountExist(account) {
|
||||||
export async function selectUserByAccountExist(account) {
|
|
||||||
const exist = await User.exists({ account: account })
|
const exist = await User.exists({ account: account })
|
||||||
return exist !== null
|
return exist !== null
|
||||||
}
|
},
|
||||||
|
async createUser(user) {
|
||||||
export async function createUser(user) {
|
|
||||||
return User.create(user)
|
return User.create(user)
|
||||||
}
|
},
|
||||||
|
async updateUserById(id, user) {
|
||||||
export async function updateUserById(id, user) {
|
|
||||||
return User.findByIdAndUpdate(id, user)
|
return User.findByIdAndUpdate(id, user)
|
||||||
}
|
},
|
||||||
|
async updateUserByLoginDate(id, loginDate) {
|
||||||
export async function updateUserByLoginDate(id, loginDate) {
|
|
||||||
return User.findByIdAndUpdate(id, { lastLoginDate: loginDate })
|
return User.findByIdAndUpdate(id, { lastLoginDate: loginDate })
|
||||||
}
|
},
|
||||||
|
async deleteUserById(id) {
|
||||||
export async function deleteUserById(id) {
|
|
||||||
return User.findByIdAndDelete(id)
|
return User.findByIdAndDelete(id)
|
||||||
}
|
},
|
||||||
|
async deleteAllUser() {
|
||||||
export async function deleteAllUser() {
|
|
||||||
return User.deleteMany()
|
return User.deleteMany()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default userRepository
|
export default userRepository
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
// routes/userRoutes.js
|
|
||||||
import express from 'express'
|
import express from 'express'
|
||||||
import userController from '../controllers/userController.js'
|
import userController from '../controllers/userController.js'
|
||||||
|
|
||||||
|
|||||||
@ -25,10 +25,6 @@ const userService = {
|
|||||||
throw new Error(messages.user.passwordIncorrect)
|
throw new Error(messages.user.passwordIncorrect)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新用户的最后登录时间
|
|
||||||
user.lastLoginDate = new Date()
|
|
||||||
await userRepository.updateUserByLoginDate(user.id, user.lastLoginDate)
|
|
||||||
|
|
||||||
return user
|
return user
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user