import { $fetch } from 'ofetch' import { createError, defineEventHandler, getQuery } from 'h3' import { useRuntimeConfig } from '#imports' import { getTenantFromContext } from '../../utils/tenant' /** * 文章详情 * GET /api/article/detail?id=123 * 代理到 CMS: /cms/cms-article/{id} */ export default defineEventHandler(async (event) => { const config = useRuntimeConfig() const ctx = getTenantFromContext(event, config) const query = getQuery(event) const modulesApiBase = config.public.modulesApiBase as string if (!query.id) { throw createError({ statusCode: 400, statusMessage: 'Missing id parameter' }) } let res: any try { res = await $fetch(`/cms/cms-article/${query.id}`, { baseURL: modulesApiBase, headers: { TenantId: ctx.tenantId } }) } catch (error: any) { throw createError({ statusCode: error?.statusCode || error?.response?.status || 502, statusMessage: error?.statusMessage || 'Failed to fetch article detail' }) } // C 端不展示草稿(1)/下架(2)/已删除文章:status 非 0(已发布) 或 deleted=1 视为不存在 // 上游真实枚举:0=已发布 1=草稿 2=下架(与早期假设相反,已于 2026-07-29 校正) // 上游详情接口不校验状态,需在此拦截,否则可通过 /article/:id 直接访问未发布内容。 // 上游对不存在/未发布文章常返回 {code:1, message:"文章ID不存在"}(无 data), // 此时 res.code !== 0,必须 404,否则扁平后的对象为 truthy,前端会误判为「文章存在」渲染空页。 const detail = res?.data ?? res if (typeof res?.code === 'number' && res.code !== 0) { throw createError({ statusCode: 404, statusMessage: 'Article not found or unpublished' }) } if (!detail || detail.status === undefined || detail.status !== 0 || detail.deleted === 1) { throw createError({ statusCode: 404, statusMessage: 'Article not found or unpublished' }) } // 文章附件:上游 files 可能是 JSON 字符串或数组,容错解析为数组后随扁平数据返回 let files: any[] = [] if (typeof detail.files === 'string' && detail.files.trim()) { try { const arr = JSON.parse(detail.files) if (Array.isArray(arr)) files = arr } catch { // 解析失败则忽略,不阻断详情返回 } } else if (Array.isArray(detail.files)) { files = detail.files } // 字段兼容归一化:上游 CMS 不同版本字段名不一致,统一补齐, // 避免前端模板的 / 副标题取不到值而渲染空白。 // - content(富文本正文):部分版本放在 description,兜底回退(content 优先) // - subtitle(副标题):上游多数版本返回 summary,兜底回退 if (detail && typeof detail === 'object') { if (detail.content == null || detail.content === '') { detail.content = detail.description || '' } if (detail.subtitle == null || detail.subtitle === '') { detail.subtitle = detail.summary || '' } } // 返回扁平数据,去掉上游 {code, message, data} 包装层 // 前端 useFetch
直接访问 article.title / article.content 等字段 return { ...detail, files: files.length ? files : undefined, } })