新建一个文件夹model,在这个文件夹下新建weaponSkinModel.js文件
// model/weaponSkinModel.js
const { pool } = require('../config/db');
// 👉 第1个功能:查询所有武器
async function getAllWeaponSkins() {
try {
const [rows] = await pool.execute('SELECT * FROM weapon_skins ORDER BY id DESC');
return rows;
} catch (error) {
console.error('❌ 查询所有数据失败:', error.message);
throw error;
}
}
// 只暴露当前开发的功能
module.exports = {
getAllWeaponSkins
};
创建外层index.js文件,开始对上面代码做测试,注意层级,并在index.js文件中,创建测试代码
// index.js
const { testPoolConnection } = require('./config/db');
const weaponSkinModel = require('./model/weaponSkinModel');
// 👉 测试 1:查询所有数据(对应 getAllWeaponSkins 功能)
async function testGetAllWeaponSkins() {
console.log('===== 开始测试:查询所有数据 =====');
try {
// 先测试连接池
await testPoolConnection();
// 调用查询函数
const result = await weaponSkinModel.getAllWeaponSkins();
console.log('查询成功!结果:');
console.log(result.length > 0 ? result : '暂无数据');
} catch (error) {
console.log('查询失败!原因:', error.message);
}
console.log('===== 测试结束:查询所有数据 =====\n');
}
// 👉 执行当前测试(只运行这一个)
testGetAllWeaponSkins();
运行index.js文件,可以看到控制台输出正常