refactor: 将项目从 CommonJS 迁移到 ES6 模块
- 更新所有文件的导入和导出语法,使用 ES6 模块格式 - 修改 package.json,添加 "type": "module" 配置 - 调整部分代码结构以适应 ES6 模块
This commit is contained in:
parent
04885717c2
commit
4edd3c2a26
47
app.js
47
app.js
@ -1,22 +1,37 @@
|
||||
const createError = require('http-errors')
|
||||
const express = require('express')
|
||||
const path = require('path')
|
||||
const logger = require('morgan')
|
||||
const cors = require('cors')
|
||||
const session = require('express-session')
|
||||
const { RedisStore } = require('connect-redis')
|
||||
const Redis = require('ioredis')
|
||||
const cookieParser = require('cookie-parser')
|
||||
const indexRouter = require('./routes/index')
|
||||
const userRouter = require('./routes/userRouter')
|
||||
const accountRouter = require('./routes/accountRouter')
|
||||
require('dotenv').config()
|
||||
import createError from 'http-errors'
|
||||
|
||||
import express from 'express'
|
||||
|
||||
import path from 'path'
|
||||
|
||||
import logger from 'morgan'
|
||||
|
||||
import cors from 'cors'
|
||||
|
||||
import session from 'express-session'
|
||||
|
||||
import { RedisStore } from 'connect-redis'
|
||||
|
||||
import Redis from 'ioredis'
|
||||
|
||||
import cookieParser from 'cookie-parser'
|
||||
|
||||
import indexRouter from './routes/index'
|
||||
|
||||
import userRouter from './routes/userRouter'
|
||||
|
||||
import accountRouter from './routes/accountRouter'
|
||||
|
||||
import { config } from 'dotenv'
|
||||
|
||||
// mongodb数据库连接
|
||||
const { connectMongoDB } = require('./config/mongodbConfig')
|
||||
const loginUtil = require('./utils/loginUtil')
|
||||
const { HTTP_STATUS } = require('./common/constant/httpStatus')
|
||||
import { connectMongoDB } from './config/mongodbConfig'
|
||||
|
||||
import { HTTP_STATUS } from './common/constant/httpStatus'
|
||||
|
||||
import loginUtil from './utils/loginUtil'
|
||||
|
||||
config()
|
||||
// 初始化 Redis 客户端
|
||||
const redisClient = new Redis({
|
||||
host: process.env.REDIS_HOST,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/**
|
||||
* HTTP 状态码常量
|
||||
*/
|
||||
const HTTP_STATUS = {
|
||||
export const HTTP_STATUS = {
|
||||
// 信息响应 (100–199)
|
||||
/** @type {number} 继续 */
|
||||
CONTINUE: 100,
|
||||
@ -67,4 +67,4 @@ const HTTP_STATUS = {
|
||||
GATEWAY_TIMEOUT: 504
|
||||
}
|
||||
|
||||
module.exports = { HTTP_STATUS }
|
||||
export default { HTTP_STATUS }
|
||||
|
||||
@ -16,4 +16,4 @@ class FetchResult {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FetchResult
|
||||
export default FetchResult
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// messages.js
|
||||
module.exports = {
|
||||
export default {
|
||||
user: {
|
||||
// 成功消息
|
||||
created: 'user created',
|
||||
@ -7,6 +7,7 @@ module.exports = {
|
||||
deleted: 'user deleted',
|
||||
login: 'login successful',
|
||||
logout: 'logout successful',
|
||||
exists: 'user exists',
|
||||
|
||||
// 错误消息
|
||||
not_found: 'user not found',
|
||||
|
||||
@ -1,6 +1,10 @@
|
||||
const mongoose = require('mongoose')
|
||||
const logger = require('morgan')
|
||||
require('dotenv').config()
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
import logger from 'morgan'
|
||||
|
||||
import { config } from 'dotenv'
|
||||
|
||||
config()
|
||||
|
||||
// 使用环境变量存储敏感信息
|
||||
const account = process.env.MONGO_ACCOUNT
|
||||
@ -10,7 +14,7 @@ const port = process.env.MONGO_PORT || '27017'
|
||||
|
||||
let isConnected = false
|
||||
|
||||
exports.connectMongoDB = async function () {
|
||||
export async function connectMongoDB() {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
logger(account, password, host, port)
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
const { body, validationResult } = require('express-validator')
|
||||
const logger = require('morgan')
|
||||
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')
|
||||
import { body, validationResult } from 'express-validator'
|
||||
import logger from 'morgan'
|
||||
import userService from '../services/userService'
|
||||
import FetchResult from '../common/web/fetchResult'
|
||||
import messages from '../config/messages'
|
||||
import { HTTP_STATUS } from '../common/constant/httpStatus'
|
||||
import { SearchQuery } from '../models/search'
|
||||
|
||||
exports.getAllUsers = async (res) => {
|
||||
export async function getAllUsers(res) {
|
||||
try {
|
||||
const users = await userService.getUserList()
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', users)
|
||||
@ -15,7 +15,7 @@ exports.getAllUsers = async (res) => {
|
||||
}
|
||||
}
|
||||
|
||||
exports.findUserList = async (req, res) => {
|
||||
export async function findUserList(req, res) {
|
||||
try {
|
||||
const { page, size, sort } = req.query
|
||||
const search = new SearchQuery({ page: page, size: size, sort: sort })
|
||||
@ -28,7 +28,7 @@ exports.findUserList = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
exports.createUser = [
|
||||
export const 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'),
|
||||
@ -63,7 +63,7 @@ exports.createUser = [
|
||||
}
|
||||
]
|
||||
|
||||
exports.login = [
|
||||
export const login = [
|
||||
body('account').notEmpty().withMessage('Account is required'),
|
||||
body('password').notEmpty().withMessage('Password is required'),
|
||||
async (req, res, next) => {
|
||||
@ -99,7 +99,7 @@ exports.login = [
|
||||
}
|
||||
]
|
||||
|
||||
exports.logout = async (req, res) => {
|
||||
export async function logout(req, res) {
|
||||
try {
|
||||
req.session.destroy()
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.OK, messages.user.logout)
|
||||
@ -109,7 +109,7 @@ exports.logout = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
exports.getUserExist = async (req, res) => {
|
||||
export async function getUserExists(req, res) {
|
||||
try {
|
||||
const { account } = req.query
|
||||
|
||||
@ -118,7 +118,7 @@ exports.getUserExist = async (req, res) => {
|
||||
if (!exist) {
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.NOT_FOUND, messages.user.not_found)
|
||||
}
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, messages.user.exist)
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, messages.user.exists)
|
||||
} catch (err) {
|
||||
logger('Error checking user existence: ', err)
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error')
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
class SearchQuery {
|
||||
export class SearchQuery {
|
||||
constructor({ size, page, sort, filters }) {
|
||||
this.size = size
|
||||
this.page = page
|
||||
@ -26,4 +26,4 @@ class SearchResult {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { SearchQuery, SearchResult }
|
||||
export default { SearchQuery, SearchResult }
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
"name": "express",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node ./bin/www",
|
||||
"nodemon": "nodemon ./bin/www",
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
// routes/userRoutes.js
|
||||
const express = require('express')
|
||||
const userController = require('../controllers/userController')
|
||||
import express from 'express'
|
||||
|
||||
import userController from '../controllers/userController'
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
router.get('/', userController.getUserExist)
|
||||
|
||||
module.exports = router
|
||||
export default router
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
const express = require('express')
|
||||
const router = express.Router()
|
||||
const userController = require('../controllers/userController')
|
||||
import express from 'express'
|
||||
|
||||
import userController from '../controllers/userController'
|
||||
|
||||
const router = express.Router()
|
||||
router.get('/', function (req, res) {
|
||||
if (!req.session.views) {
|
||||
req.session.views = 1
|
||||
@ -15,4 +16,4 @@ router.post('/login', userController.login)
|
||||
|
||||
router.post('/logout', userController.logout)
|
||||
|
||||
module.exports = router
|
||||
export default router
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// routes/userRoutes.js
|
||||
const express = require('express')
|
||||
const userController = require('../controllers/userController')
|
||||
import userController from '../controllers/userController'
|
||||
|
||||
import express from 'express'
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
@ -8,4 +9,4 @@ router.get('/', userController.getAllUsers)
|
||||
router.post('/', userController.createUser)
|
||||
router.get('/list', userController.findUserList)
|
||||
|
||||
module.exports = router
|
||||
export default router
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
const userMapper = require('../repositories/userRepository')
|
||||
const logger = require('morgan')
|
||||
const messages = require('../config/messages')
|
||||
const { comparePassword } = require('../utils/hashUtils')
|
||||
import userMapper from '../repositories/userRepository'
|
||||
import logger from 'morgan'
|
||||
import messages from '../config/messages'
|
||||
import { comparePassword } from '../utils/hashUtils'
|
||||
|
||||
/**
|
||||
* 用户登录
|
||||
@ -10,7 +10,7 @@ const { comparePassword } = require('../utils/hashUtils')
|
||||
* @returns {Promise<Object>} - 登录成功返回用户信息
|
||||
* @throws {Error} - 如果用户不存在或密码不正确
|
||||
*/
|
||||
exports.login = async (account, password) => {
|
||||
export async function login(account, password) {
|
||||
const user = await userMapper.selectUserByAccount(account)
|
||||
|
||||
// 用户不存在
|
||||
@ -19,7 +19,7 @@ exports.login = async (account, password) => {
|
||||
}
|
||||
|
||||
// 密码不匹配
|
||||
const isMatch = await comparePassword(password, user.password)
|
||||
const isMatch = comparePassword(password, user.password)
|
||||
if (!isMatch) {
|
||||
throw new Error(messages.user.passwordIncorrect)
|
||||
}
|
||||
@ -36,16 +36,16 @@ exports.login = async (account, password) => {
|
||||
* @param {string} account
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
exports.getUserExists = async (account) => {
|
||||
export async function getUserExists(account) {
|
||||
return userMapper.selectUserByAccountExist(account)
|
||||
}
|
||||
|
||||
// Removed the unnecessary try-catch block and simplified the function
|
||||
exports.getAllUser = async () => {
|
||||
export async function getAllUser() {
|
||||
return await userMapper.selectAllUser()
|
||||
}
|
||||
|
||||
exports.getUserList = async (searchQuery) => {
|
||||
export async function getUserList(searchQuery) {
|
||||
return userMapper.selectUserList(searchQuery)
|
||||
}
|
||||
|
||||
@ -55,7 +55,7 @@ exports.getUserList = async (searchQuery) => {
|
||||
* @returns {Promise<Object>} - 创建成功的用户信息
|
||||
* @throws {Error} - 如果用户已存在或事务失败
|
||||
*/
|
||||
exports.createUser = async (user) => {
|
||||
export async function createUser(user) {
|
||||
const { account } = user
|
||||
const session = await userMapper.startTransaction()
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
const bcrypt = require('bcrypt')
|
||||
import bcrypt from 'bcrypt'
|
||||
|
||||
/**
|
||||
* 加密密码
|
||||
@ -15,8 +15,8 @@ async function hashPassword(password) {
|
||||
* @param {string} hashedPassword 哈希密码
|
||||
* @returns {boolean} 是否匹配
|
||||
*/
|
||||
async function comparePassword(password, hashedPassword) {
|
||||
export async function comparePassword(password, hashedPassword) {
|
||||
return bcrypt.compare(password, hashedPassword)
|
||||
}
|
||||
|
||||
module.exports = { hashPassword, comparePassword }
|
||||
export default { hashPassword, comparePassword }
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
const FetchResult = require('../common/web/fetchResult.js')
|
||||
const { HTTP_STATUS } = require('../common/constant/httpStatus.js')
|
||||
import FetchResult from '../common/web/fetchResult.js'
|
||||
|
||||
exports.authenticateSession = async (req, res, next) => {
|
||||
import { HTTP_STATUS } from '../common/constant/httpStatus.js'
|
||||
|
||||
export async function authenticateSession(req, res, next) {
|
||||
if (req.session.user) {
|
||||
next()
|
||||
} else {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user