增加一个根据id,扣减库存的功能。函数入参为:id,stock两个参数
// model/weaponSkinModel.js(新增)
async function updateWeaponSkinStock(id, newStock) {
// 校验
if (!id) throw new Error('ID 不能为空');
if (typeof newStock !== 'number' || newStock < 0) {
throw new Error('库存必须为非负整数');
}
try {
const [result] = await pool.execute(
'UPDATE weapon_skins SET stock = ? WHERE id = ?',
[newStock, id]
);
if (result.affectedRows === 0) {
throw new Error(未找到 ID=${id} 的数据);
}
return {
success: true,
message: 库存更新为 ${newStock},
affectedRows: result.affectedRows
};
} catch (error) {
console.error(❌ 修改 ID=${id} 库存失败:, error.message);
throw error;
}
}
// 更新暴露
module.exports = {
// *
updateWeaponSkinStock // 新增
};
// index.js(新增测试函数)
// 👉 测试:修改库存(对应 updateWeaponSkinStock 功能)
async function testUpdateWeaponSkinStock() {
console.log('===== 开始测试:修改库存 =====');
const testId = 2; // 用实际存在的 ID
const newStock = 15;
try {
await testPoolConnection();
// 执行修改
const result = await weaponSkinModel.updateWeaponSkinStock(testId, newStock);
console.log('修改结果:', result);
} catch (error) {
console.log('修改失败!原因:', error.message);
}
console.log('===== 测试结束:修改库存 =====\n');
}
// 👉 执行当前测试
testUpdateWeaponSkinStock();