refactor: 优化项目结构和代码
- 更新 .gitignore 文件,排除 Idea 项目配置 - 移除 vuepress 缓存目录 - 优化 app.js 中的错误处理和状态码导入- 调整 CORS 配置,移除未使用的 allowdHeaders - 更新 hashUtils.js 中的密码处理函数 - 优化 index.js 中的路由定义 - 更新 mongodbConfig.js 中的数据库连接逻辑 - 升级 express到 5.0.0- 更新 mongoose 到 8.7.1
This commit is contained in:
parent
352323262c
commit
8741389ef5
2
.gitignore
vendored
2
.gitignore
vendored
@ -102,7 +102,6 @@ dist
|
|||||||
|
|
||||||
# vuepress v2.x temp and cache directory
|
# vuepress v2.x temp and cache directory
|
||||||
.temp
|
.temp
|
||||||
.cache
|
|
||||||
|
|
||||||
# Docusaurus cache and generated files
|
# Docusaurus cache and generated files
|
||||||
.docusaurus
|
.docusaurus
|
||||||
@ -128,3 +127,4 @@ dist
|
|||||||
.yarn/build-state.yml
|
.yarn/build-state.yml
|
||||||
.yarn/install-state.gz
|
.yarn/install-state.gz
|
||||||
.pnp.*
|
.pnp.*
|
||||||
|
/.idea/
|
||||||
|
|||||||
8
app.js
8
app.js
@ -15,6 +15,7 @@ require('dotenv').config()
|
|||||||
// mongodb数据库连接
|
// mongodb数据库连接
|
||||||
const { connectMongoDB } = require('./config/mongodbConfig')
|
const { connectMongoDB } = require('./config/mongodbConfig')
|
||||||
const loginUtil = require('./utils/loginUtil')
|
const loginUtil = require('./utils/loginUtil')
|
||||||
|
const { HTTP_STATUS } = require('./common/constant/httpStatus')
|
||||||
|
|
||||||
// 初始化 Redis 客户端
|
// 初始化 Redis 客户端
|
||||||
const redisClient = new Redis({
|
const redisClient = new Redis({
|
||||||
@ -48,8 +49,7 @@ app.use(
|
|||||||
const corsOptions = {
|
const corsOptions = {
|
||||||
origin: 'http://localhost:5173', // 指定允许的源
|
origin: 'http://localhost:5173', // 指定允许的源
|
||||||
credentials: true, // 允许发送凭据(如 cookies)
|
credentials: true, // 允许发送凭据(如 cookies)
|
||||||
optionsSuccessStatus: 200,
|
optionsSuccessStatus: 200
|
||||||
allowdHeaders: ['Content-Type', 'Authorization']
|
|
||||||
}
|
}
|
||||||
|
|
||||||
app.use(cors(corsOptions))
|
app.use(cors(corsOptions))
|
||||||
@ -63,7 +63,7 @@ async function startServer() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
startServer()
|
startServer().then((r) => logger(r))
|
||||||
|
|
||||||
app.use('/', indexRouter)
|
app.use('/', indexRouter)
|
||||||
app.use('/user', loginUtil.authenticateSession, userRouter)
|
app.use('/user', loginUtil.authenticateSession, userRouter)
|
||||||
@ -75,7 +75,7 @@ app.use(function (req, res, next) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// error handler
|
// error handler
|
||||||
app.use(function (err, req, res, next) {
|
app.use(function (err, req, res) {
|
||||||
// set locals, only providing error in development
|
// set locals, only providing error in development
|
||||||
res.locals.message = err.message
|
res.locals.message = err.message
|
||||||
res.locals.error = req.app.get('env') === 'development' ? err : {}
|
res.locals.error = req.app.get('env') === 'development' ? err : {}
|
||||||
|
|||||||
57
bin/www
57
bin/www
@ -3,50 +3,47 @@
|
|||||||
/**
|
/**
|
||||||
* Module dependencies.
|
* Module dependencies.
|
||||||
*/
|
*/
|
||||||
|
const app = require('../app')
|
||||||
var app = require('../app');
|
const debug = require('debug')('express:server')
|
||||||
var debug = require('debug')('express:server');
|
const http = require('http')
|
||||||
var http = require('http');
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get port from environment and store in Express.
|
* Get port from environment and store in Express.
|
||||||
*/
|
*/
|
||||||
|
const port = normalizePort(process.env.PORT || '3000')
|
||||||
var port = normalizePort(process.env.PORT || '3000');
|
app.set('port', port)
|
||||||
app.set('port', port);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create HTTP server.
|
* Create HTTP server.
|
||||||
*/
|
*/
|
||||||
|
const server = http.createServer(app)
|
||||||
var server = http.createServer(app);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Listen on provided port, on all network interfaces.
|
* Listen on provided port, on all network interfaces.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
server.listen(port);
|
server.listen(port)
|
||||||
server.on('error', onError);
|
server.on('error', onError)
|
||||||
server.on('listening', onListening);
|
server.on('listening', onListening)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalize a port into a number, string, or false.
|
* Normalize a port into a number, string, or false.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function normalizePort(val) {
|
function normalizePort(val) {
|
||||||
var port = parseInt(val, 10);
|
const port = parseInt(val, 10)
|
||||||
|
|
||||||
if (isNaN(port)) {
|
if (isNaN(port)) {
|
||||||
// named pipe
|
// named pipe
|
||||||
return val;
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
if (port >= 0) {
|
if (port >= 0) {
|
||||||
// port number
|
// port number
|
||||||
return port;
|
return port
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -55,25 +52,25 @@ function normalizePort(val) {
|
|||||||
|
|
||||||
function onError(error) {
|
function onError(error) {
|
||||||
if (error.syscall !== 'listen') {
|
if (error.syscall !== 'listen') {
|
||||||
throw error;
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
var bind = typeof port === 'string'
|
const bind = typeof port === 'string'
|
||||||
? 'Pipe ' + port
|
? 'Pipe ' + port
|
||||||
: 'Port ' + port;
|
: 'Port ' + port
|
||||||
|
|
||||||
// handle specific listen errors with friendly messages
|
// handle specific listen errors with friendly messages
|
||||||
switch (error.code) {
|
switch (error.code) {
|
||||||
case 'EACCES':
|
case 'EACCES':
|
||||||
console.error(bind + ' requires elevated privileges');
|
console.error(bind + ' requires elevated privileges')
|
||||||
process.exit(1);
|
process.exit(1)
|
||||||
break;
|
break
|
||||||
case 'EADDRINUSE':
|
case 'EADDRINUSE':
|
||||||
console.error(bind + ' is already in use');
|
console.error(bind + ' is already in use')
|
||||||
process.exit(1);
|
process.exit(1)
|
||||||
break;
|
break
|
||||||
default:
|
default:
|
||||||
throw error;
|
throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -82,9 +79,9 @@ function onError(error) {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
function onListening() {
|
function onListening() {
|
||||||
var addr = server.address();
|
const addr = server.address()
|
||||||
var bind = typeof addr === 'string'
|
const bind = typeof addr === 'string'
|
||||||
? 'pipe ' + addr
|
? 'pipe ' + addr
|
||||||
: 'port ' + addr.port;
|
: 'port ' + addr.port
|
||||||
debug('Listening on ' + bind);
|
debug('Listening on ' + bind)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -23,7 +23,7 @@ exports.connectMongoDB = async function () {
|
|||||||
try {
|
try {
|
||||||
const mongoDBUrl = `mongodb://${account}:${password}@${host}:${port}`
|
const mongoDBUrl = `mongodb://${account}:${password}@${host}:${port}`
|
||||||
|
|
||||||
mongoose.connect(mongoDBUrl)
|
await mongoose.connect(mongoDBUrl)
|
||||||
|
|
||||||
mongoose.connection.on('open', () => {
|
mongoose.connection.on('open', () => {
|
||||||
console.log('MongoDB 连接成功')
|
console.log('MongoDB 连接成功')
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
const { body, validationResult } = require('express-validator')
|
const { body, validationResult } = require('express-validator')
|
||||||
|
const logger = require('morgan')
|
||||||
const userService = require('../services/userService')
|
const userService = require('../services/userService')
|
||||||
const FetchResult = require('../common/web/fetchResult')
|
const FetchResult = require('../common/web/fetchResult')
|
||||||
const messages = require('../config/messages')
|
const messages = require('../config/messages')
|
||||||
@ -50,7 +51,7 @@ exports.createUser = [
|
|||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const user = req.body
|
const user = req.body
|
||||||
await userService.create_user(user)
|
await userService.createUser(user)
|
||||||
return FetchResult.formatResult(res, HTTP_STATUS.CREATED, messages.user.created)
|
return FetchResult.formatResult(res, HTTP_STATUS.CREATED, messages.user.created)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger('Error creating user: ', err)
|
logger('Error creating user: ', err)
|
||||||
@ -88,9 +89,7 @@ exports.login = [
|
|||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { account, password } = req.body
|
const { account, password } = req.body
|
||||||
|
req.session.user = await userService.login(account, password)
|
||||||
const user = await userService.login(account, password)
|
|
||||||
req.session.user = user
|
|
||||||
return FetchResult.formatResult(res, 200, messages.user.login)
|
return FetchResult.formatResult(res, 200, messages.user.login)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.message === messages.user.not_found) {
|
if (err.message === messages.user.not_found) {
|
||||||
|
|||||||
@ -22,8 +22,7 @@ UserSchema.pre('save', async function (next) {
|
|||||||
try {
|
try {
|
||||||
console.log(user.password)
|
console.log(user.password)
|
||||||
|
|
||||||
const hashedPassword = await hashPassword(user.password)
|
user.password = await hashPassword(user.password)
|
||||||
user.password = hashedPassword
|
|
||||||
next()
|
next()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error)
|
next(error)
|
||||||
|
|||||||
929
package-lock.json
generated
929
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -13,14 +13,14 @@
|
|||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"debug": "~2.6.9",
|
"debug": "~2.6.9",
|
||||||
"dotenv": "^16.4.7",
|
"dotenv": "^16.4.7",
|
||||||
"express": "^4.19.2",
|
"express": "5.0.0",
|
||||||
"express-async-handler": "^1.2.0",
|
"express-async-handler": "^1.2.0",
|
||||||
"express-session": "^1.18.1",
|
"express-session": "^1.18.1",
|
||||||
"express-validator": "^7.2.0",
|
"express-validator": "^7.2.0",
|
||||||
"http-errors": "~1.6.3",
|
"http-errors": "~1.6.3",
|
||||||
"ioredis": "^5.4.2",
|
"ioredis": "^5.4.2",
|
||||||
"jade": "^0.29.0",
|
"jade": "^0.29.0",
|
||||||
"mongoose": "^8.3.4",
|
"mongoose": "8.7.1",
|
||||||
"morgan": "~1.9.1",
|
"morgan": "~1.9.1",
|
||||||
"nodemon": "^3.1.0",
|
"nodemon": "^3.1.0",
|
||||||
"redis": "^4.7.0"
|
"redis": "^4.7.0"
|
||||||
|
|||||||
@ -2,21 +2,21 @@ const UserModel = require('../models/userModel')
|
|||||||
const { SearchResult } = require('../models/Search')
|
const { SearchResult } = require('../models/Search')
|
||||||
|
|
||||||
exports.startTransaction = async () => {
|
exports.startTransaction = async () => {
|
||||||
const seesion = await UserModel.startSession()
|
const session = await UserModel.startSession()
|
||||||
seesion.startTransaction()
|
session.startTransaction()
|
||||||
return seesion
|
return session
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.commitTransaction = async (session) => {
|
exports.commitTransaction = async (session) => {
|
||||||
return await session.commitTransaction()
|
return session.commitTransaction()
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.rollbackTransaction = async (session) => {
|
exports.rollbackTransaction = async (session) => {
|
||||||
return await session.abortTransaction()
|
return session.abortTransaction()
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.selectAllUser = async () => {
|
exports.selectAllUser = async () => {
|
||||||
return await UserModel.find()
|
return UserModel.find()
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.selectUserList = async (search = {}) => {
|
exports.selectUserList = async (search = {}) => {
|
||||||
@ -58,23 +58,23 @@ exports.selectUserList = async (search = {}) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
exports.selectUserById = async (id) => {
|
exports.selectUserById = async (id) => {
|
||||||
return await UserModel.findById(id)
|
return UserModel.findById(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.selectUserByAccount = async (account) => {
|
exports.selectUserByAccount = async (account) => {
|
||||||
return await UserModel.findOne({ account: account })
|
return UserModel.findOne({ account: account })
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.selectUserByEmail = async (email) => {
|
exports.selectUserByEmail = async (email) => {
|
||||||
return await UserModel.findOne({ email: email })
|
return UserModel.findOne({ email: email })
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.selectUserByUsername = async (username) => {
|
exports.selectUserByUsername = async (username) => {
|
||||||
return await UserModel.findOne({ username: username })
|
return UserModel.findOne({ username: username })
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.selectUserByPhone = async (phone) => {
|
exports.selectUserByPhone = async (phone) => {
|
||||||
return await UserModel.findOne({ phone: phone })
|
return UserModel.findOne({ phone: phone })
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.selectUserByAccountExist = async (account) => {
|
exports.selectUserByAccountExist = async (account) => {
|
||||||
@ -83,21 +83,21 @@ exports.selectUserByAccountExist = async (account) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
exports.createUser = async (user) => {
|
exports.createUser = async (user) => {
|
||||||
return await UserModel.create(user)
|
return UserModel.create(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.updateUserById = async (id, user) => {
|
exports.updateUserById = async (id, user) => {
|
||||||
return await UserModel.findByIdAndUpdate(id, user)
|
return UserModel.findByIdAndUpdate(id, user)
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.updateUserByLoginDate = async (id, loginDate) => {
|
exports.updateUserByLoginDate = async (id, loginDate) => {
|
||||||
return await UserModel.findByIdAndUpdate(id, { last_login_date: loginDate })
|
return UserModel.findByIdAndUpdate(id, { last_login_date: loginDate })
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.deleteUserById = async (id) => {
|
exports.deleteUserById = async (id) => {
|
||||||
return await UserModel.findByIdAndDelete(id)
|
return UserModel.findByIdAndDelete(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.deleteAllUser = async () => {
|
exports.deleteAllUser = async () => {
|
||||||
return await UserModel.deleteMany()
|
return UserModel.deleteMany()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
var express = require('express')
|
const express = require('express')
|
||||||
var router = express.Router()
|
const router = express.Router()
|
||||||
const userController = require('../controllers/userController')
|
const userController = require('../controllers/userController')
|
||||||
|
|
||||||
router.get('/', function (req, res, next) {
|
router.get('/', function (req, res) {
|
||||||
if (!req.session.views) {
|
if (!req.session.views) {
|
||||||
req.session.views = 1
|
req.session.views = 1
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@ -2,7 +2,6 @@ const userMapper = require('../repositories/userRepository')
|
|||||||
const logger = require('morgan')
|
const logger = require('morgan')
|
||||||
const messages = require('../config/messages')
|
const messages = require('../config/messages')
|
||||||
const { comparePassword } = require('../utils/hashUtils')
|
const { comparePassword } = require('../utils/hashUtils')
|
||||||
const { SearchQuery } = require('../models/Search')
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户登录
|
* 用户登录
|
||||||
@ -64,7 +63,7 @@ exports.createUser = async (user) => {
|
|||||||
// 检查用户是否已存在
|
// 检查用户是否已存在
|
||||||
const existingUser = await userMapper.selectUserByAccount(account)
|
const existingUser = await userMapper.selectUserByAccount(account)
|
||||||
if (existingUser) {
|
if (existingUser) {
|
||||||
throw new Error(messages.user.already_exists)
|
return new Error(messages.user.already_exists)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建新用户
|
// 创建新用户
|
||||||
|
|||||||
@ -9,11 +9,11 @@ exports.isNotEmpty = function (obj) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (obj instanceof String) {
|
if (obj instanceof String) {
|
||||||
return obj === '' ? false : true
|
return obj !== ''
|
||||||
}
|
}
|
||||||
|
|
||||||
if (obj instanceof Array) {
|
if (obj instanceof Array) {
|
||||||
return Array.length(obj) === 0 ? false : true
|
return Array.length(obj) !== 0
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,21 +2,19 @@ const bcrypt = require('bcrypt')
|
|||||||
|
|
||||||
async function hashPassword(password) {
|
async function hashPassword(password) {
|
||||||
try {
|
try {
|
||||||
const hashedPassword = await bcrypt.hash(password, 10)
|
return await bcrypt.hash(password, 10)
|
||||||
return hashedPassword
|
} catch (err) {
|
||||||
} catch (error) {
|
console.error('Error hashing password:', err)
|
||||||
console.error('Error hashing password:', error)
|
throw err // 重新抛出错误以便调用方处理
|
||||||
throw error // 重新抛出错误以便调用方处理
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function comparePassword(password, hashedPassword) {
|
async function comparePassword(password, hashedPassword) {
|
||||||
try {
|
try {
|
||||||
const isMatch = await bcrypt.compare(password, hashedPassword)
|
return await bcrypt.compare(password, hashedPassword)
|
||||||
return isMatch
|
} catch (err) {
|
||||||
} catch (error) {
|
console.error('Error comparing password:', err)
|
||||||
console.error('Error comparing password:', error)
|
throw err // 重新抛出错误以便调用方处理
|
||||||
throw error // 重新抛出错误以便调用方处理
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user