refactor(config): 优化错误消息和日志记录

- 更新错误消息格式,使用驼峰命名法
- 添加服务器错误消息
- 用 logger 替代 console.log 记录日志
- 更新 MongoDB 连接日志
- 优化用户控制器中的错误处理
- 移除 SearchQuery 类中的无效代码
- 更新 package.json 中的脚本
- 移除未使用的 StringUtil 工具类
- 优化 hashUtils 中的密码加密和比较函数
This commit is contained in:
LingandRX 2025-01-04 23:25:29 +08:00
parent 321a2566de
commit 602c0fff4b
9 changed files with 41 additions and 69 deletions

View File

@ -3,6 +3,6 @@
"semi": false,
"tabWidth": 2,
"singleQuote": true,
"printWidth": 100,
"printWidth": 150,
"trailingComma": "none"
}

View File

@ -10,10 +10,13 @@ module.exports = {
// 错误消息
not_found: 'user not found',
already_exists: 'user already exists',
account_password_not_match: 'account and password not match',
account_not_match: 'account not match',
password_not_match: 'password not match',
password_incorrect: 'password incorrect'
alreadyExists: 'user already exists',
accountPasswordNotMatch: 'account and password not match',
accountNotMatch: 'account not match',
passwordNotMatch: 'password not match',
passwordIncorrect: 'password incorrect'
},
server: {
error: 'server error'
}
}

View File

@ -1,5 +1,6 @@
const mongoose = require('mongoose')
require('dotenv').config() // 加载 .env 文件
const logger = require('morgan')
require('dotenv').config()
// 使用环境变量存储敏感信息
const account = process.env.MONGO_ACCOUNT
@ -11,12 +12,12 @@ let isConnected = false
exports.connectMongoDB = async function () {
if (process.env.NODE_ENV === 'development') {
console.log(account, password, host, port)
logger(account, password, host, port)
}
// 如果已经连接,不再重复连接
if (isConnected) {
console.log('MongoDB 已经连接')
logger('MongoDB 已经连接')
return
}
@ -26,21 +27,21 @@ exports.connectMongoDB = async function () {
await mongoose.connect(mongoDBUrl)
mongoose.connection.on('open', () => {
console.log('MongoDB 连接成功')
logger('MongoDB 连接成功')
isConnected = true
})
mongoose.connection.on('error', (err) => {
console.error('MongoDB 连接错误:', err.message)
logger('MongoDB 连接错误:', err.message)
isConnected = false
})
mongoose.connection.on('close', () => {
console.log('MongoDB 连接关闭')
logger('MongoDB 连接关闭')
isConnected = false
})
} catch (err) {
console.error('MongoDB 连接初始化失败:', err.message)
logger('MongoDB 连接初始化失败:', err.message)
throw err
}
}

View File

@ -4,7 +4,7 @@ const userService = require('../services/userService')
const FetchResult = require('../common/web/fetchResult')
const messages = require('../config/messages')
const { HTTP_STATUS } = require('../common/constant/httpStatus')
const { SearchQuery } = require('../models/Search')
const { SearchQuery } = require('../models/search')
exports.getAllUsers = async (res) => {
try {
@ -58,11 +58,7 @@ exports.createUser = [
if (err.message === messages.user.already_exists) {
return FetchResult.formatResult(res, HTTP_STATUS.CONFLICT, messages.user.already_exists)
}
return FetchResult.formatResult(
res,
HTTP_STATUS.INTERNAL_SERVER_ERROR,
'Internal server error'
)
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
}
}
]
@ -90,19 +86,15 @@ exports.login = [
try {
const { account, password } = req.body
req.session.user = await userService.login(account, password)
return FetchResult.formatResult(res, 200, messages.user.login)
return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, messages.user.login)
} catch (err) {
if (err.message === messages.user.not_found) {
return FetchResult.formatResult(res, 401, messages.user.account_password_not_match)
return FetchResult.formatResult(res, HTTP_STATUS.NOT_FOUND, messages.user.accountPasswordNotMatch)
}
logger('Error logging in: ', 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')
}
}
]
@ -113,11 +105,7 @@ exports.logout = async (req, res) => {
return FetchResult.formatResult(res, HTTP_STATUS.OK, messages.user.logout)
} catch (err) {
logger('Error logging out: ', 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')
}
}
@ -128,9 +116,9 @@ exports.getUserExist = async (req, res) => {
const exist = await userService.get_user_exist(account)
if (!exist) {
return FetchResult.formatResult(res, 404, messages.user.not_found)
return FetchResult.formatResult(res, HTTP_STATUS.NOT_FOUND, messages.user.not_found)
}
return FetchResult.formatResult(res, 200, messages.user.exist)
return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, messages.user.exist)
} catch (err) {
logger('Error checking user existence: ', err)
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')

View File

@ -9,9 +9,6 @@ class SearchQuery {
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')
}

View File

@ -4,7 +4,8 @@
"private": true,
"scripts": {
"start": "node ./bin/www",
"nodemon": "nodemon ./bin/www"
"nodemon": "nodemon ./bin/www",
"push": "git push -u github main && git push -u origin main"
},
"dependencies": {
"bcrypt": "^5.1.1",

View File

@ -1,5 +1,5 @@
const UserModel = require('../models/userModel')
const { SearchResult } = require('../models/Search')
const { SearchResult } = require('../models/search')
exports.startTransaction = async () => {
const session = await UserModel.startSession()

View File

@ -1,19 +0,0 @@
/**
* 判断是否为空
* @param {*} obj 任意值
* @returns {Boolean} obj是否为空
*/
exports.isNotEmpty = function (obj) {
if (obj === null || obj === undefined || Object.keys(obj).length === 0) {
return false
}
if (obj instanceof String) {
return obj !== ''
}
if (obj instanceof Array) {
return Array.length(obj) !== 0
}
return true
}

View File

@ -1,21 +1,22 @@
const bcrypt = require('bcrypt')
/**
* 加密密码
* @param {string} password 密码
* @returns password 加密后的密码
*/
async function hashPassword(password) {
try {
return await bcrypt.hash(password, 10)
} catch (err) {
console.error('Error hashing password:', err)
throw err // 重新抛出错误以便调用方处理
}
return bcrypt.hash(password, 10)
}
/**
* 比较密码
* @param {string} password 密码
* @param {string} hashedPassword 哈希密码
* @returns {boolean} 是否匹配
*/
async function comparePassword(password, hashedPassword) {
try {
return await bcrypt.compare(password, hashedPassword)
} catch (err) {
console.error('Error comparing password:', err)
throw err // 重新抛出错误以便调用方处理
}
return bcrypt.compare(password, hashedPassword)
}
module.exports = { hashPassword, comparePassword }