storeJson.ts 1.05 KB
import { isLosslessNumber, parse, toSafeNumberOrThrow } from 'lossless-json';

const MONEY_FIELD =
  /^(?:costDecoration|costMonthly|costLabor|costTotal|marketFee\d+Value|sunshine\d+Value)$/;

function isStoreEndpoint(url?: string) {
  if (!url) return false;
  try {
    const path = new URL(url, 'http://store-api.local').pathname;
    return /^\/(?:api\/)?store\/(?:approval|listing)(?:\/|$)/.test(path);
  } catch {
    return false;
  }
}

/**
 * 仅门店业务响应使用无损解析。ID 与金额保留服务端数字原文;
 * 页码、状态码、层级和开关仍为经过安全转换的普通数值。
 */
export function parseStoreResponse(raw: string, url?: string): unknown {
  if (!isStoreEndpoint(url)) return JSON.parse(raw) as unknown;

  return parse(raw, (key, value) => {
    if (!isLosslessNumber(value)) return value;
    if (
      key === 'id' ||
      key.endsWith('Id') ||
      key === 'createBy' ||
      key === 'updateBy' ||
      MONEY_FIELD.test(key)
    )
      return value.value;
    return toSafeNumberOrThrow(value.value);
  });
}