1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/src/common/utils/downloadFile.ts
Sebastian Malton c3dcf0e838 Refactor the Extensions settings page (#2221)
Signed-off-by: Sebastian Malton <sebastian@malton.name>
2021-04-26 11:53:51 -04:00

47 lines
1.0 KiB
TypeScript

import request from "request";
export interface DownloadFileOptions {
url: string;
gzip?: boolean;
timeout?: number;
}
export interface DownloadFileTicket<T> {
url: string;
promise: Promise<T>;
cancel(): void;
}
export function downloadFile({ url, timeout, gzip = true }: DownloadFileOptions): DownloadFileTicket<Buffer> {
const fileChunks: Buffer[] = [];
const req = request(url, { gzip, timeout });
const promise: Promise<Buffer> = new Promise((resolve, reject) => {
req.on("data", (chunk: Buffer) => {
fileChunks.push(chunk);
});
req.once("error", err => {
reject({ url, err });
});
req.once("complete", () => {
resolve(Buffer.concat(fileChunks));
});
});
return {
url,
promise,
cancel() {
req.abort();
}
};
}
export function downloadJson(args: DownloadFileOptions): DownloadFileTicket<any> {
const { promise, ...rest } = downloadFile(args);
return {
promise: promise.then(res => JSON.parse(res.toString())),
...rest
};
}