From 602c0fff4b3a413c0fe7cf9119f79d2b9ae435da Mon Sep 17 00:00:00 2001 From: LingandRX Date: Sat, 4 Jan 2025 23:25:29 +0800 Subject: [PATCH] =?UTF-8?q?refactor(config):=20=E4=BC=98=E5=8C=96=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E6=B6=88=E6=81=AF=E5=92=8C=E6=97=A5=E5=BF=97=E8=AE=B0?= =?UTF-8?q?=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 更新错误消息格式,使用驼峰命名法 - 添加服务器错误消息 - 用 logger 替代 console.log 记录日志 - 更新 MongoDB 连接日志 - 优化用户控制器中的错误处理 - 移除 SearchQuery 类中的无效代码 - 更新 package.json 中的脚本 - 移除未使用的 StringUtil 工具类 - 优化 hashUtils 中的密码加密和比较函数 --- .prettierrc | 2 +- config/messages.js | 13 ++++++++----- config/mongodbConfig.js | 15 ++++++++------- controllers/userController.js | 28 ++++++++-------------------- models/Search.js | 3 --- package.json | 3 ++- repositories/userRepository.js | 2 +- utils/StringUtil.js | 19 ------------------- utils/hashUtils.js | 25 +++++++++++++------------ 9 files changed, 41 insertions(+), 69 deletions(-) delete mode 100644 utils/StringUtil.js diff --git a/.prettierrc b/.prettierrc index ecdf3e0..df78ea1 100644 --- a/.prettierrc +++ b/.prettierrc @@ -3,6 +3,6 @@ "semi": false, "tabWidth": 2, "singleQuote": true, - "printWidth": 100, + "printWidth": 150, "trailingComma": "none" } diff --git a/config/messages.js b/config/messages.js index 3b7365c..3c59ada 100644 --- a/config/messages.js +++ b/config/messages.js @@ -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' } } diff --git a/config/mongodbConfig.js b/config/mongodbConfig.js index 109eb2f..3b36d6b 100644 --- a/config/mongodbConfig.js +++ b/config/mongodbConfig.js @@ -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 } } diff --git a/controllers/userController.js b/controllers/userController.js index 28d8026..59482af 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -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') diff --git a/models/Search.js b/models/Search.js index c85ab13..27cc3db 100644 --- a/models/Search.js +++ b/models/Search.js @@ -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') } diff --git a/package.json b/package.json index 9306ee3..54c163e 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/repositories/userRepository.js b/repositories/userRepository.js index 51249b0..6d5782d 100644 --- a/repositories/userRepository.js +++ b/repositories/userRepository.js @@ -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() diff --git a/utils/StringUtil.js b/utils/StringUtil.js deleted file mode 100644 index f401a9d..0000000 --- a/utils/StringUtil.js +++ /dev/null @@ -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 -} diff --git a/utils/hashUtils.js b/utils/hashUtils.js index 2654cd7..5995c22 100644 --- a/utils/hashUtils.js +++ b/utils/hashUtils.js @@ -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 }