From 204902247775ba104b572420d7fc394ed7cf01fd Mon Sep 17 00:00:00 2001 From: Emelia Smith Date: Thu, 8 Aug 2019 14:26:30 +0200 Subject: [PATCH] fix(api): correctly handle responses with missing content-type header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also prevents non .tgz requests from being handled as tgz requests — the previous if condition was incorrect --- src/utils/api.test.ts | 16 ++++++++++++++++ src/utils/api.ts | 10 +++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/utils/api.test.ts b/src/utils/api.test.ts index bf5824b..f110ff0 100644 --- a/src/utils/api.test.ts +++ b/src/utils/api.test.ts @@ -11,6 +11,22 @@ describe('api', () => { }; describe('handleResponseType', () => { + test('should handle missing Content-Type', async () => { + const response: Response = { + url: 'http://localhost:8080/-/packages', + ok: false, + // @ts-ignore + headers: { + get: () => null, + } as Headers, + } as Response; + + const handled = await handleResponseType(response); + + // Should this actually return [false, null] ? + expect(handled).toBeUndefined(); + }); + test('should test tgz scenario', async () => { const blob = new Blob(['foo']); const blobPromise = Promise.resolve(blob); diff --git a/src/utils/api.ts b/src/utils/api.ts index 3d95a5e..1dd45a4 100644 --- a/src/utils/api.ts +++ b/src/utils/api.ts @@ -8,20 +8,20 @@ import '../../types'; */ export function handleResponseType(response: Response): Promise<[boolean, Blob | string]> | Promise { if (response.headers) { - const contentType = response.headers.get('Content-Type') as string; - if (contentType.includes('application/pdf')) { + const contentType = response.headers.get('Content-Type'); + if (contentType && contentType.includes('application/pdf')) { return Promise.all([response.ok, response.blob()]); } - if (contentType.includes('application/json')) { + if (contentType && contentType.includes('application/json')) { return Promise.all([response.ok, response.json()]); } // it includes all text types - if (contentType.includes('text/')) { + if (contentType && contentType.includes('text/')) { return Promise.all([response.ok, response.text()]); } // unfortunatelly on download files there is no header available - if (response.url && response.url.endsWith('.tgz') !== null) { + if (response.url && response.url.endsWith('.tgz') === true) { return Promise.all([response.ok, response.blob()]); } }