refactor: 将项目从 CommonJS 迁移到 ES6 模块

- 更新所有文件的导入和导出语法,使用 ES6 模块格式
- 修改 package.json,添加 "type": "module" 配置
- 调整部分代码结构以适应 ES6 模块
This commit is contained in:
LingandRX 2025-01-04 23:54:03 +08:00
parent 04885717c2
commit 4edd3c2a26
14 changed files with 91 additions and 66 deletions

47
app.js
View File

@ -1,22 +1,37 @@
const createError = require('http-errors') import createError from 'http-errors'
const express = require('express')
const path = require('path') import express from 'express'
const logger = require('morgan')
const cors = require('cors') import path from 'path'
const session = require('express-session')
const { RedisStore } = require('connect-redis') import logger from 'morgan'
const Redis = require('ioredis')
const cookieParser = require('cookie-parser') import cors from 'cors'
const indexRouter = require('./routes/index')
const userRouter = require('./routes/userRouter') import session from 'express-session'
const accountRouter = require('./routes/accountRouter')
require('dotenv').config() 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数据库连接 // mongodb数据库连接
const { connectMongoDB } = require('./config/mongodbConfig') import { connectMongoDB } from './config/mongodbConfig'
const loginUtil = require('./utils/loginUtil')
const { HTTP_STATUS } = require('./common/constant/httpStatus')
import { HTTP_STATUS } from './common/constant/httpStatus'
import loginUtil from './utils/loginUtil'
config()
// 初始化 Redis 客户端 // 初始化 Redis 客户端
const redisClient = new Redis({ const redisClient = new Redis({
host: process.env.REDIS_HOST, host: process.env.REDIS_HOST,

View File

@ -1,7 +1,7 @@
/** /**
* HTTP 状态码常量 * HTTP 状态码常量
*/ */
const HTTP_STATUS = { export const HTTP_STATUS = {
// 信息响应 (100199) // 信息响应 (100199)
/** @type {number} 继续 */ /** @type {number} 继续 */
CONTINUE: 100, CONTINUE: 100,
@ -67,4 +67,4 @@ const HTTP_STATUS = {
GATEWAY_TIMEOUT: 504 GATEWAY_TIMEOUT: 504
} }
module.exports = { HTTP_STATUS } export default { HTTP_STATUS }

View File

@ -16,4 +16,4 @@ class FetchResult {
} }
} }
module.exports = FetchResult export default FetchResult

View File

@ -1,5 +1,5 @@
// messages.js // messages.js
module.exports = { export default {
user: { user: {
// 成功消息 // 成功消息
created: 'user created', created: 'user created',
@ -7,6 +7,7 @@ module.exports = {
deleted: 'user deleted', deleted: 'user deleted',
login: 'login successful', login: 'login successful',
logout: 'logout successful', logout: 'logout successful',
exists: 'user exists',
// 错误消息 // 错误消息
not_found: 'user not found', not_found: 'user not found',

View File

@ -1,6 +1,10 @@
const mongoose = require('mongoose') import mongoose from 'mongoose'
const logger = require('morgan')
require('dotenv').config() import logger from 'morgan'
import { config } from 'dotenv'
config()
// 使用环境变量存储敏感信息 // 使用环境变量存储敏感信息
const account = process.env.MONGO_ACCOUNT const account = process.env.MONGO_ACCOUNT
@ -10,7 +14,7 @@ const port = process.env.MONGO_PORT || '27017'
let isConnected = false let isConnected = false
exports.connectMongoDB = async function () { 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)
} }

View File

@ -1,12 +1,12 @@
const { body, validationResult } = require('express-validator') import { body, validationResult } from 'express-validator'
const logger = require('morgan') import logger from 'morgan'
const userService = require('../services/userService') import userService from '../services/userService'
const FetchResult = require('../common/web/fetchResult') import FetchResult from '../common/web/fetchResult'
const messages = require('../config/messages') import messages from '../config/messages'
const { HTTP_STATUS } = require('../common/constant/httpStatus') import { HTTP_STATUS } from '../common/constant/httpStatus'
const { SearchQuery } = require('../models/search') import { SearchQuery } from '../models/search'
exports.getAllUsers = async (res) => { export async function getAllUsers(res) {
try { try {
const users = await userService.getUserList() const users = await userService.getUserList()
return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', users) 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 { try {
const { page, size, sort } = req.query const { page, size, sort } = req.query
const search = new SearchQuery({ page: page, size: size, sort: sort }) 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').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'),
body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'), 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('account').notEmpty().withMessage('Account is required'),
body('password').notEmpty().withMessage('Password is required'), body('password').notEmpty().withMessage('Password is required'),
async (req, res, next) => { async (req, res, next) => {
@ -99,7 +99,7 @@ exports.login = [
} }
] ]
exports.logout = async (req, res) => { export async function logout(req, res) {
try { try {
req.session.destroy() req.session.destroy()
return FetchResult.formatResult(res, HTTP_STATUS.OK, messages.user.logout) 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 { try {
const { account } = req.query const { account } = req.query
@ -118,7 +118,7 @@ exports.getUserExist = async (req, res) => {
if (!exist) { if (!exist) {
return FetchResult.formatResult(res, HTTP_STATUS.NOT_FOUND, messages.user.not_found) 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) { } catch (err) {
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')

View File

@ -1,4 +1,4 @@
class SearchQuery { export class SearchQuery {
constructor({ size, page, sort, filters }) { constructor({ size, page, sort, filters }) {
this.size = size this.size = size
this.page = page this.page = page
@ -26,4 +26,4 @@ class SearchResult {
} }
} }
module.exports = { SearchQuery, SearchResult } export default { SearchQuery, SearchResult }

View File

@ -2,6 +2,7 @@
"name": "express", "name": "express",
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"type": "module",
"scripts": { "scripts": {
"start": "node ./bin/www", "start": "node ./bin/www",
"nodemon": "nodemon ./bin/www", "nodemon": "nodemon ./bin/www",

View File

@ -1,9 +1,10 @@
// routes/userRoutes.js // routes/userRoutes.js
const express = require('express') import express from 'express'
const userController = require('../controllers/userController')
import userController from '../controllers/userController'
const router = express.Router() const router = express.Router()
router.get('/', userController.getUserExist) router.get('/', userController.getUserExist)
module.exports = router export default router

View File

@ -1,7 +1,8 @@
const express = require('express') import express from 'express'
const router = express.Router()
const userController = require('../controllers/userController')
import userController from '../controllers/userController'
const router = express.Router()
router.get('/', function (req, res) { router.get('/', function (req, res) {
if (!req.session.views) { if (!req.session.views) {
req.session.views = 1 req.session.views = 1
@ -15,4 +16,4 @@ router.post('/login', userController.login)
router.post('/logout', userController.logout) router.post('/logout', userController.logout)
module.exports = router export default router

View File

@ -1,6 +1,7 @@
// routes/userRoutes.js // routes/userRoutes.js
const express = require('express') import userController from '../controllers/userController'
const userController = require('../controllers/userController')
import express from 'express'
const router = express.Router() const router = express.Router()
@ -8,4 +9,4 @@ router.get('/', userController.getAllUsers)
router.post('/', userController.createUser) router.post('/', userController.createUser)
router.get('/list', userController.findUserList) router.get('/list', userController.findUserList)
module.exports = router export default router

View File

@ -1,7 +1,7 @@
const userMapper = require('../repositories/userRepository') import userMapper from '../repositories/userRepository'
const logger = require('morgan') import logger from 'morgan'
const messages = require('../config/messages') import messages from '../config/messages'
const { comparePassword } = require('../utils/hashUtils') import { comparePassword } from '../utils/hashUtils'
/** /**
* 用户登录 * 用户登录
@ -10,7 +10,7 @@ const { comparePassword } = require('../utils/hashUtils')
* @returns {Promise<Object>} - 登录成功返回用户信息 * @returns {Promise<Object>} - 登录成功返回用户信息
* @throws {Error} - 如果用户不存在或密码不正确 * @throws {Error} - 如果用户不存在或密码不正确
*/ */
exports.login = async (account, password) => { export async function login(account, password) {
const user = await userMapper.selectUserByAccount(account) 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) { if (!isMatch) {
throw new Error(messages.user.passwordIncorrect) throw new Error(messages.user.passwordIncorrect)
} }
@ -36,16 +36,16 @@ exports.login = async (account, password) => {
* @param {string} account * @param {string} account
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
exports.getUserExists = async (account) => { export async function getUserExists(account) {
return userMapper.selectUserByAccountExist(account) return userMapper.selectUserByAccountExist(account)
} }
// Removed the unnecessary try-catch block and simplified the function // Removed the unnecessary try-catch block and simplified the function
exports.getAllUser = async () => { export async function getAllUser() {
return await userMapper.selectAllUser() return await userMapper.selectAllUser()
} }
exports.getUserList = async (searchQuery) => { export async function getUserList(searchQuery) {
return userMapper.selectUserList(searchQuery) return userMapper.selectUserList(searchQuery)
} }
@ -55,7 +55,7 @@ exports.getUserList = async (searchQuery) => {
* @returns {Promise<Object>} - 创建成功的用户信息 * @returns {Promise<Object>} - 创建成功的用户信息
* @throws {Error} - 如果用户已存在或事务失败 * @throws {Error} - 如果用户已存在或事务失败
*/ */
exports.createUser = async (user) => { export async function createUser(user) {
const { account } = user const { account } = user
const session = await userMapper.startTransaction() const session = await userMapper.startTransaction()

View File

@ -1,4 +1,4 @@
const bcrypt = require('bcrypt') import bcrypt from 'bcrypt'
/** /**
* 加密密码 * 加密密码
@ -15,8 +15,8 @@ async function hashPassword(password) {
* @param {string} hashedPassword 哈希密码 * @param {string} hashedPassword 哈希密码
* @returns {boolean} 是否匹配 * @returns {boolean} 是否匹配
*/ */
async function comparePassword(password, hashedPassword) { export async function comparePassword(password, hashedPassword) {
return bcrypt.compare(password, hashedPassword) return bcrypt.compare(password, hashedPassword)
} }
module.exports = { hashPassword, comparePassword } export default { hashPassword, comparePassword }

View File

@ -1,7 +1,8 @@
const FetchResult = require('../common/web/fetchResult.js') import FetchResult from '../common/web/fetchResult.js'
const { HTTP_STATUS } = require('../common/constant/httpStatus.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) { if (req.session.user) {
next() next()
} else { } else {