diff --git a/package.json b/package.json index dc90ded9..49ff3a62 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "openapi-typescript-codegen", - "version": "0.1.11", + "version": "0.1.12", "description": "NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification.", "author": "Ferdi Koomen", "homepage": "https://github.com/ferdikoomen/openapi-typescript-codegen", diff --git a/src/templates/core/requestUsingFetch.ts b/src/templates/core/requestUsingFetch.ts index 0f895f61..637285a6 100644 --- a/src/templates/core/requestUsingFetch.ts +++ b/src/templates/core/requestUsingFetch.ts @@ -5,6 +5,32 @@ import { Result } from './Result'; +/** + * Try to parse the content for any response status code. + * We check the "Content-Type" header to see if we need to parse the + * content as json or as plain text. + * @param response Response object from fetch + */ +async function parseBody(response: Response): Promise { + + try { + const contentType = response.headers.get('Content-Type'); + if (contentType) { + switch (contentType.toLowerCase()) { + case 'application/json': + case 'application/json; charset=utf-8': + return await response.json(); + + default: + return await response.text(); + } + } + } catch (e) { + console.error(e); + } + return null; +} + /** * Request content using the new Fetch API. This is the default API that is used and * is create for all JSON, XML and text objects. However it is limited to UTF-8. @@ -18,33 +44,11 @@ export async function requestUsingFetch(url: string, request: Readonly { + + try { + const contentType = response.headers.get('Content-Type'); + if (contentType) { + switch (contentType.toLowerCase()) { + case 'application/json': + case 'application/json; charset=utf-8': + return await response.json(); + + default: + return await response.text(); + } + } + } catch (e) { + console.error(e); + } + return null; +} + /** * Request content using the new Fetch API. This is the default API that is used and * is create for all JSON, XML and text objects. However it is limited to UTF-8. @@ -293,35 +319,13 @@ export async function requestUsingFetch(url: string, request: Readonly { + + try { + const contentType = response.headers.get('Content-Type'); + if (contentType) { + switch (contentType.toLowerCase()) { + case 'application/json': + case 'application/json; charset=utf-8': + return await response.json(); + + default: + return await response.text(); + } + } + } catch (e) { + console.error(e); + } + return null; +} + /** * Request content using the new Fetch API. This is the default API that is used and * is create for all JSON, XML and text objects. However it is limited to UTF-8. @@ -2444,35 +2481,13 @@ export async function requestUsingFetch(url: string, request: Readonly