update server/routers/back-new/features/image/image.controller.js

This commit is contained in:
xingzhe.ru
2025-07-04 00:21:13 +00:00
parent 34163788f3
commit 351ea75072

View File

@@ -110,6 +110,20 @@ async function fetchImageContent(accessToken, imageId) {
} }
} }
// 工具函数:异步重试
async function retryAsync(fn, times = 3, delay = 800) {
let lastErr;
for (let i = 0; i < times; i++) {
try {
return await fn();
} catch (err) {
lastErr = err;
if (i < times - 1 && delay) await new Promise(r => setTimeout(r, delay));
}
}
throw lastErr;
}
exports.generate = async (req, res) => { exports.generate = async (req, res) => {
const { prompt } = req.query; const { prompt } = req.query;
if (!prompt) { if (!prompt) {
@@ -122,14 +136,17 @@ exports.generate = async (req, res) => {
return res.status(500).json({ error: e.message }); return res.status(500).json({ error: e.message });
} }
try { try {
const content = await fetchChatContent(accessToken, prompt); // 1. 重试获取图片描述内容
const match = content.match(/<img src=\"(.*?)\"/); const content = await retryAsync(() => fetchChatContent(accessToken, prompt), 3, 800);
// 升级正则,兼容更多图片标签格式
const match = content.match(/<img[^>]+src=['"]([^'"]+)['"]/);
if (!match) { if (!match) {
console.error('AI生成图片出错: GigaChat未返回图片标签'); console.error('AI生成图片出错: GigaChat未返回图片标签');
return res.status(500).json({ error: 'No image generated' }); return res.status(500).json({ error: 'No image generated' });
} }
const imageId = match[1]; const imageId = match[1];
const imageData = await fetchImageContent(accessToken, imageId); // 2. 重试获取图片内容
const imageData = await retryAsync(() => fetchImageContent(accessToken, imageId), 3, 800);
res.set('Content-Type', 'image/jpeg'); res.set('Content-Type', 'image/jpeg');
res.set('X-HATEOAS', JSON.stringify(makeLinks('/gigachat', { self: '/prompt' }))); res.set('X-HATEOAS', JSON.stringify(makeLinks('/gigachat', { self: '/prompt' })));
res.send(imageData); res.send(imageData);