Files
xk-admin/packages/effects/request/src/request-client/modules/downloader.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-06-02 20:50:51 +08:00
import type { RequestClient } from '../request-client';
import type { RequestClientConfig } from '../types';
type DownloadRequestConfig = {
/**
*
* raw: 原始的AxiosResponseheadersstatus等
* body: 只返回响应数据的BODY部分(Blob)
*/
responseReturn?: 'body' | 'raw';
} & Omit<RequestClientConfig, 'responseReturn'>;
2024-06-02 20:50:51 +08:00
class FileDownloader {
private client: RequestClient;
constructor(client: RequestClient) {
this.client = client;
}
/**
*
* @param url
* @param config
* @returns config.responseReturn为'body'Blob()RequestResponse<Blob>
*/
public async download<T = Blob>(
2024-06-02 20:50:51 +08:00
url: string,
config?: DownloadRequestConfig,
): Promise<T> {
const finalConfig: DownloadRequestConfig = {
responseReturn: 'body',
2025-08-08 15:31:31 +08:00
method: 'GET',
2024-06-02 20:50:51 +08:00
...config,
responseType: 'blob',
};
// Prefer a generic request if available; otherwise, dispatch to method-specific calls.
const method = (finalConfig.method || 'GET').toUpperCase();
const clientAny = this.client as any;
2024-06-02 20:50:51 +08:00
if (typeof clientAny.request === 'function') {
return await clientAny.request(url, finalConfig);
}
const lower = method.toLowerCase();
if (typeof clientAny[lower] === 'function') {
if (['POST', 'PUT'].includes(method)) {
const { data, ...rest } = finalConfig as Record<string, any>;
return await clientAny[lower](url, data, rest);
}
return await clientAny[lower](url, finalConfig);
}
throw new Error(
`RequestClient does not support method "${method}". Please ensure the method is properly implemented in your RequestClient instance.`,
);
2024-06-02 20:50:51 +08:00
}
}
export { FileDownloader };