api.ts
1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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;
}