update at 2026-02-08 18:28:39
This commit is contained in:
67
miniprogram/utils/mp/render-api.js
Normal file
67
miniprogram/utils/mp/render-api.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const { request } = require('./wx-promisify')
|
||||
|
||||
function buildApiUrl() {
|
||||
const app = getApp()
|
||||
const apiUrl = app && app.globalData ? app.globalData.svgRenderApiUrl : ''
|
||||
if (!apiUrl) {
|
||||
throw new Error('未配置渲染 API 地址')
|
||||
}
|
||||
return apiUrl
|
||||
}
|
||||
|
||||
function normalizeResult(data) {
|
||||
if (!data || typeof data !== 'object') {
|
||||
throw new Error('渲染服务返回格式无效')
|
||||
}
|
||||
|
||||
if (typeof data.svg !== 'string' || !data.svg.trim()) {
|
||||
throw new Error('渲染服务未返回有效 SVG')
|
||||
}
|
||||
|
||||
return {
|
||||
svg: data.svg,
|
||||
width: Number(data.width) || 0,
|
||||
height: Number(data.height) || 0,
|
||||
fontName: data.fontName || 'Unknown',
|
||||
fontId: data.fontId || '',
|
||||
}
|
||||
}
|
||||
|
||||
async function renderSvgByApi(payload) {
|
||||
const app = getApp()
|
||||
const timeout = app && app.globalData && app.globalData.apiTimeoutMs
|
||||
? Number(app.globalData.apiTimeoutMs)
|
||||
: 30000
|
||||
|
||||
const response = await request({
|
||||
url: buildApiUrl(),
|
||||
method: 'POST',
|
||||
timeout,
|
||||
header: {
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
fontId: payload.fontId,
|
||||
text: payload.text,
|
||||
fontSize: payload.fontSize,
|
||||
fillColor: payload.fillColor,
|
||||
letterSpacing: payload.letterSpacing,
|
||||
maxCharsPerLine: payload.maxCharsPerLine,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response || response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw new Error(`渲染服务请求失败,状态码: ${response && response.statusCode}`)
|
||||
}
|
||||
|
||||
const body = response.data || {}
|
||||
if (!body.ok) {
|
||||
throw new Error(body.error || '渲染服务返回错误')
|
||||
}
|
||||
|
||||
return normalizeResult(body.data)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
renderSvgByApi,
|
||||
}
|
||||
Reference in New Issue
Block a user