storeDownload.ts 2.88 KB
import type { AxiosInstance } from 'axios';
import type { ListingPageParams } from './storeTypes';

const DEFAULT_FILENAME = '门店列表.xlsx';

function exportFilename(disposition: string) {
  const encoded = /filename\*\s*=\s*(?:"([^"]*)"|([^;]*))/i.exec(disposition);
  const plain = /(?:^|;)\s*filename\s*=\s*(?:"([^"]*)"|([^;]*))/i.exec(disposition);
  let filename = plain?.[1] ?? plain?.[2]?.trim() ?? DEFAULT_FILENAME;
  if (encoded) {
    try {
      const value = (encoded[1] ?? encoded[2]).trim().replace(/^[^']*'[^']*'/, '');
      filename = decodeURIComponent(value);
    } catch {
      // 不合法的 filename* 回退到普通文件名。
    }
  }
  return filename.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').trim() || DEFAULT_FILENAME;
}

function invalidDownload(payload: unknown): Error {
  let body = payload;
  if (typeof body === 'string') {
    try {
      body = JSON.parse(body);
    } catch {
      body = null;
    }
  }
  if (body && typeof body === 'object' && 'message' in body && typeof body.message === 'string') {
    return Object.assign(new Error(body.message), {
      code: 'code' in body ? body.code : undefined,
      data: 'data' in body ? body.data : undefined,
    });
  }
  return new Error('导出响应不是可下载的文件');
}

/** 复用鉴权/签名拦截器,同时保留文件响应和 JSON 业务错误的不同处理。 */
export async function downloadStoreExport(http: AxiosInstance, params: ListingPageParams) {
  let filename = DEFAULT_FILENAME;
  let mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const response: unknown = await http.request({
    method: 'GET',
    url: '/store/listing/export',
    params,
    responseType: 'arraybuffer',
    transformResponse: [
      (raw: ArrayBuffer | string, headers) => {
        filename = exportFilename(String(headers['content-disposition'] ?? ''));
        mime = String(headers['content-type'] ?? mime);
        // http 的 JSON 错误拦截需要原始文本,不能把 ArrayBuffer stringify 成 {}。
        return /\bjson\b/i.test(mime) && typeof raw !== 'string'
          ? new TextDecoder().decode(raw)
          : raw;
      },
    ],
  });

  // 非 JSON 响应由共享拦截器包装为 { data, headers },先取出文件内容。
  const payload =
    response && typeof response === 'object' && 'headers' in response && 'data' in response
      ? response.data
      : response;
  if (!(payload instanceof ArrayBuffer)) throw invalidDownload(payload);

  const blob = new Blob([payload], { type: mime });
  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = objectUrl;
  link.download = filename;
  link.hidden = true;
  document.body.appendChild(link);
  try {
    link.click();
  } finally {
    link.remove();
    // 让浏览器先消费下载链接,再释放其内存。
    setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
  }
}