api.ts 1.79 KB
import type {
  SopMaterialPreviewApiError,
  SopMaterialPreviewApiResponse,
} from '@single-pages/contracts';
import { buildBackendApiPath } from '@single-pages/config';

const backendApiPath = (pathname: string) => buildBackendApiPath(pathname, {
  hostname: globalThis.location?.hostname,
  envBasePath: (import.meta as ImportMeta & { env: { VITE_BACKEND_API_BASE_PATH?: string } }).env
    .VITE_BACKEND_API_BASE_PATH,
});

export class SopMaterialPreviewRequestError extends Error {
  readonly code: string;
  readonly details?: unknown;

  constructor(code: string, message: string, details?: unknown) {
    super(message);
    this.name = 'SopMaterialPreviewRequestError';
    this.code = code;
    this.details = details;
  }
}

function isSopMaterialPreviewError(value: unknown): value is SopMaterialPreviewApiError {
  return Boolean(value)
    && typeof value === 'object'
    && value !== null
    && 'error' in value
    && Boolean((value as SopMaterialPreviewApiError).error)
    && typeof (value as SopMaterialPreviewApiError).error.code === 'string';
}

export async function fetchSopMaterialPreview(
  actionId: string,
  queryParams?: URLSearchParams,
): Promise<SopMaterialPreviewApiResponse> {
  const params = new URLSearchParams(queryParams);
  params.set('actionId', actionId);

  const response = await fetch(backendApiPath(`/api/sop-material-preview?${params.toString()}`));

  const json = (await response.json().catch(() => null)) as unknown;

  if (!response.ok) {
    if (isSopMaterialPreviewError(json)) {
      throw new SopMaterialPreviewRequestError(json.error.code, json.error.message, json.error.details);
    }

    throw new SopMaterialPreviewRequestError('SOP_MATERIAL_PREVIEW_REQUEST_FAILED', '素材加载失败,请稍后重试');
  }

  return json as SopMaterialPreviewApiResponse;
}