Ai config

This commit is contained in:
董海洋
2026-05-26 13:37:55 +08:00
parent 55452a2d21
commit 0c7ed3498d
42 changed files with 1264 additions and 767 deletions
+38 -6
View File
@@ -1,5 +1,23 @@
const { query } = require('../config/database')
const { toRelativeUrl } = require('../utils/image-url')
const { toRelativeUrl, processGoodsImages } = require('../utils/image-url')
const { paginate } = require('../utils/pagination')
const path = require('path')
const fs = require('fs')
function parseImages(images) {
if (!images) return []
try {
const parsed = typeof images === 'string' ? JSON.parse(images) : images
return Array.isArray(parsed) ? parsed : []
} catch { return [] }
}
function deleteImageFiles(urls) {
for (const url of urls) {
const filePath = path.join(__dirname, '..', 'public', url.replace(/^\//, ''))
fs.unlink(filePath, () => {})
}
}
async function getGoods(ctx) {
let sql = 'SELECT * FROM goods WHERE 1=1'
@@ -37,16 +55,20 @@ async function getGoods(ctx) {
sql += ' ORDER BY id DESC'
}
if (ctx.query.limit) {
if (ctx.query.limit && !ctx.query.page) {
sql += ' LIMIT ?'
params.push(parseInt(ctx.query.limit))
const goods = await query(sql, params)
ctx.body = { code: 200, data: processGoodsImages(goods) }
return
}
const goods = await query(sql, params)
const result = await paginate(query, sql, params, ctx.query.page, ctx.query.pageSize)
if (result.data) result.data = processGoodsImages(result.data)
ctx.body = {
code: 200,
data: goods
...result
}
}
@@ -57,7 +79,7 @@ async function getGoodsById(ctx) {
if (goods.length > 0) {
ctx.body = {
code: 200,
data: goods[0]
data: processGoodsImages(goods)[0]
}
} else {
ctx.body = {
@@ -129,7 +151,6 @@ async function updateGoods(ctx) {
return
}
// 将图片URL转换为相对路径存储
const relativeImages = (images || []).map(img => toRelativeUrl(img))
const sql = `UPDATE goods SET
@@ -153,8 +174,14 @@ async function updateGoods(ctx) {
]
try {
const existing = await query('SELECT images FROM goods WHERE id = ?', [goodsId])
const result = await query(sql, params)
if (result.affectedRows > 0) {
if (existing.length > 0 && images) {
const oldImages = parseImages(existing[0].images)
const oldFiles = oldImages.filter(u => u.startsWith('/uploads/') && !relativeImages.includes(u))
deleteImageFiles(oldFiles)
}
ctx.body = {
code: 200,
message: '更新成功'
@@ -178,8 +205,13 @@ async function deleteGoods(ctx) {
const goodsId = parseInt(ctx.params.id)
try {
const existing = await query('SELECT images FROM goods WHERE id = ?', [goodsId])
const result = await query('DELETE FROM goods WHERE id = ?', [goodsId])
if (result.affectedRows > 0) {
if (existing.length > 0) {
const oldImages = parseImages(existing[0].images)
deleteImageFiles(oldImages.filter(u => u.startsWith('/uploads/')))
}
ctx.body = {
code: 200,
message: '删除成功'