122 lines
4.6 KiB
TypeScript
122 lines
4.6 KiB
TypeScript
import { z } from 'zod'
|
|
import { desktopAssert, DesktopClientError } from './contract.mjs'
|
|
|
|
const dimensions = z.object({
|
|
length: z.number().nullable(),
|
|
width: z.number().nullable(),
|
|
height: z.number().nullable(),
|
|
unit: z.string().nullable(),
|
|
})
|
|
const attributes = z.record(z.union([z.string(), dimensions])).nullable()
|
|
const image = z.object({
|
|
url: z.string(),
|
|
kind: z.enum(['main', 'sku', 'reference', 'whiteBackground']),
|
|
signed: z.boolean().nullable(),
|
|
expiresAt: z.string().nullable(),
|
|
})
|
|
const productResponse = z.object({
|
|
success: z.literal(true),
|
|
data: z.object({
|
|
spu: z.string(),
|
|
productName: z.string().nullable(),
|
|
brandName: z.string().nullable(),
|
|
categoryName: z.string().nullable(),
|
|
shared: z.object({
|
|
dimensions: dimensions.nullable(),
|
|
sizeText: z.string().nullable(),
|
|
material: z.string().nullable(),
|
|
description: z.string().nullable(),
|
|
attributes,
|
|
sellingPoints: z.array(z.string()),
|
|
}),
|
|
mainImages: z.array(image),
|
|
barcodes: z.array(z.object({
|
|
barcode: z.string(),
|
|
skuCode: z.string().nullable(),
|
|
skuName: z.string().nullable(),
|
|
colorName: z.string().nullable(),
|
|
dimensions: dimensions.nullable(),
|
|
spec: z.string().nullable(),
|
|
sizeText: z.string().nullable(),
|
|
attributes,
|
|
sellingPoints: z.array(z.string()),
|
|
images: z.array(image),
|
|
updatedAt: z.string(),
|
|
})),
|
|
}),
|
|
})
|
|
const productNotFoundResponse = z.object({
|
|
success: z.literal(false),
|
|
error: z.object({ code: z.literal('PRODUCT_001') }),
|
|
})
|
|
|
|
const timeoutMs = 15_000
|
|
const timeoutCodes = ['UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']
|
|
|
|
export async function desktopProductPlatformSpu(params: URLSearchParams) {
|
|
const spu = params.get('spu')?.trim()
|
|
desktopAssert(spu, '请输入商品 SPU', 400)
|
|
|
|
const origin = process.env.PRODUCT_PLATFORM_BASE_URL?.trim() ?? ''
|
|
const key = process.env.PRODUCT_PLATFORM_BY_SPU_API_KEY?.trim() ?? ''
|
|
desktopAssert(
|
|
/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(origin) && URL.canParse(origin) && /^[\x20-\x7e\x80-\xff]+$/.test(key),
|
|
'产品平台联动未配置,请联系管理员', 503, 'product_platform_misconfigured',
|
|
)
|
|
|
|
const url = new URL('/api/external/products/by-spu', origin)
|
|
url.searchParams.set('spu', spu!)
|
|
const signal = AbortSignal.timeout(timeoutMs)
|
|
let response: Response
|
|
let payload: unknown
|
|
try {
|
|
response = await fetch(url, {
|
|
method: 'GET',
|
|
headers: { Accept: 'application/json', 'X-API-Key': key },
|
|
cache: 'no-store',
|
|
redirect: 'manual',
|
|
signal,
|
|
})
|
|
if (response.status === 200) {
|
|
payload = await response.json()
|
|
} else if (response.status === 404 && response.headers.get('content-type')?.toLowerCase().includes('application/json')) {
|
|
try {
|
|
payload = await response.json()
|
|
} catch {
|
|
payload = null
|
|
}
|
|
} else {
|
|
await response.body?.cancel()
|
|
}
|
|
} catch (error) {
|
|
const failure = error as { name?: string; cause?: { code?: string } } | null
|
|
if (signal.aborted || failure?.name === 'TimeoutError' || timeoutCodes.includes(failure?.cause?.code ?? '')) {
|
|
throw new DesktopClientError('产品平台请求超时,请稍后重试', 504, 'product_platform_timeout')
|
|
}
|
|
if (failure?.name === 'SyntaxError') {
|
|
throw new DesktopClientError('产品平台返回的资料格式异常,请联系管理员', 502, 'product_platform_invalid_response')
|
|
}
|
|
throw new DesktopClientError('产品平台暂时无法连接,请稍后重试', 502, 'product_platform_unreachable')
|
|
}
|
|
|
|
if (response.status === 404) {
|
|
if (productNotFoundResponse.safeParse(payload).success) {
|
|
throw new DesktopClientError('产品平台未找到该 SPU 资料', 404, 'product_not_found')
|
|
}
|
|
throw new DesktopClientError('产品平台查询接口暂不可用,请联系管理员', 502, 'product_platform_upstream_error')
|
|
}
|
|
if (response.status === 401 || response.status === 403) {
|
|
throw new DesktopClientError('产品平台鉴权失败,请联系管理员', 502, 'product_platform_auth_failed')
|
|
}
|
|
if (response.status === 504) {
|
|
throw new DesktopClientError('产品平台请求超时,请稍后重试', 504, 'product_platform_timeout')
|
|
}
|
|
desktopAssert(response.status === 200, '产品平台响应异常,请稍后重试', 502, 'product_platform_upstream_error')
|
|
|
|
const result = productResponse.safeParse(payload)
|
|
if (!result.success) {
|
|
throw new DesktopClientError('产品平台返回的资料格式异常,请联系管理员', 502, 'product_platform_invalid_response')
|
|
}
|
|
return { source: 'product_platform' as const, ...result.data.data }
|
|
}
|