68 lines
1.6 KiB
JavaScript
68 lines
1.6 KiB
JavaScript
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,
|
|
}
|