remote-api.ts
2.35 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import type { AxiosInstance } from 'axios';
import type { HttpMethod, RemoteRequest } from '@uj/contracts';
import { requestViaHost } from './subapp';
interface Envelope<T> {
data: T;
[key: string]: unknown;
}
export interface BlobResponse {
blob: Blob;
headers: Record<string, string>;
}
/**
* ApiClient 的子应用替身。
*
* 与老项目 `src/api/core/client.ts` 的公开面逐字对齐(get/post/put/del/getBlob、
* protected readonly http),业务模块 `class Store extends ApiClient` 因此无需改动——
* 只是继承目标被 alias 指到了这里。
*
* 差别只有一处:call() 不再调本地 axios,而是把完整 config 交给主壳注入的
* props.request。签名、验签、公钥、context-path、401 统一登出仍全项目只有一份。
*
* `this.http` 做成 duck-typed 的 AxiosInstance:storeDownload.ts 会把 http 传进
* downloadStoreExport 并附带自定义 transformResponse 回调。因为 wujie 的 props
* 是引用传递(同源 iframe,非 postMessage 序列化),函数可以原样送到主壳的
* axios.request,ArrayBuffer 与 content-disposition 的解析逻辑因此能完整保留。
*/
export class RemoteApiClient {
protected readonly http = {
request: (config: RemoteRequest) => requestViaHost()(config),
} as unknown as AxiosInstance;
protected get<T>(url: string, params?: Record<string, unknown>): Promise<T> {
return this.call<T>('GET', url, { params });
}
protected post<T>(url: string, data?: unknown): Promise<T> {
return this.call<T>('POST', url, { data });
}
protected put<T>(url: string, data?: unknown): Promise<T> {
return this.call<T>('PUT', url, { data });
}
protected del<T>(url: string, params?: Record<string, unknown>): Promise<T> {
return this.call<T>('DELETE', url, { params });
}
protected async getBlob(url: string, params?: Record<string, unknown>): Promise<BlobResponse> {
const resp = (await requestViaHost()({
method: 'GET',
url,
params,
responseType: 'blob',
})) as { data: Blob; headers?: Record<string, string> };
return { blob: resp.data, headers: resp.headers ?? {} };
}
private call<T>(
method: HttpMethod,
url: string,
extra: Record<string, unknown> = {},
): Promise<T> {
return requestViaHost()({ method, url, ...extra }).then((res) => (res as Envelope<T>).data);
}
}