Make simpleReq typesafe

This commit is contained in:
Michal Vaniš 2024-03-10 15:05:11 +01:00
parent e63cff7a52
commit bd4cfe4e7a

View file

@ -20,19 +20,23 @@ export async function downloadFile(url: string, file: string, options: RequestOp
);
}
export function simpleReq(url: string, options: RequestOptions = {}) {
export function simpleReq(url: string, options: RequestOptions = {}): Promise<IncomingMessage> {
return new Promise<IncomingMessage>((resolve, reject) => {
get(url, options, res => {
const { statusCode, statusMessage, headers } = res;
if (statusCode! >= 400) return void reject(`${statusCode}: ${statusMessage} - ${url}`);
if (statusCode! >= 300) return simpleReq(headers.location!, options).then(resolve).catch(reject);
if (statusCode && statusCode >= 400) return reject(new Error(`${statusCode}: ${statusMessage} - ${url}`));
if (statusCode && statusCode >= 300 && headers.location) {
return simpleReq(headers.location, options).then(resolve).catch(reject);
}
resolve(res);
}).on("error", err => {
reject(new Error(`Network error: ${err.message}`));
});
});
}
export async function simpleGet(url: string, options: RequestOptions = {}) {
try {
const res = await simpleReq(url, options);
return new Promise<Buffer>((resolve, reject) => {
@ -42,4 +46,7 @@ export async function simpleGet(url: string, options: RequestOptions = {}) {
res.on("data", chunk => chunks.push(chunk));
res.once("end", () => resolve(Buffer.concat(chunks)));
});
} catch (e) {
console.log(e);
}
}