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); + } }