From bd4cfe4e7ab46ea4844acc896dd1bd65f8349617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Vani=C5=A1?= Date: Sun, 10 Mar 2024 15:05:11 +0100 Subject: [PATCH] Make simpleReq typesafe --- src/main/utils/http.ts | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/main/utils/http.ts b/src/main/utils/http.ts index 9a98384..12e14a0 100644 --- a/src/main/utils/http.ts +++ b/src/main/utils/http.ts @@ -20,26 +20,33 @@ 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 { return new Promise((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 = {}) { - const res = await simpleReq(url, options); + try { + const res = await simpleReq(url, options); - return new Promise((resolve, reject) => { - const chunks = [] as Buffer[]; + return new Promise((resolve, reject) => { + const chunks = [] as Buffer[]; - res.once("error", reject); - res.on("data", chunk => chunks.push(chunk)); - res.once("end", () => resolve(Buffer.concat(chunks))); - }); + res.once("error", reject); + res.on("data", chunk => chunks.push(chunk)); + res.once("end", () => resolve(Buffer.concat(chunks))); + }); + } catch (e) { + console.log(e); + } }