From fec374417528bf05199ccc64e0978a135a6c3da3 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 22 Apr 2019 09:18:11 -0700 Subject: [PATCH] fix: use native fetch in the browser (#75) --- .gitignore | 1 + src/gaxios.ts | 12 +++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 97170d5a..dded0be4 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ build/ coverage yarn.lock .vscode +dist/ diff --git a/src/gaxios.ts b/src/gaxios.ts index e5d16e6a..21b6c828 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -13,7 +13,7 @@ import * as extend from 'extend'; import {Agent} from 'https'; -import fetch, {Response} from 'node-fetch'; +import nodeFetch, {Response as NodeFetchResponse} from 'node-fetch'; import * as qs from 'querystring'; import * as stream from 'stream'; import * as url from 'url'; @@ -23,6 +23,7 @@ import {isBrowser} from './isbrowser'; import {getRetryConfig} from './retry'; const URL = isBrowser() ? window.URL : url.URL; +const fetch = isBrowser() ? window.fetch : nodeFetch; // tslint:disable-next-line variable-name no-any let HttpsProxyAgent: any; @@ -89,8 +90,8 @@ export class Gaxios { } } - private async getResponseData(opts: GaxiosOptions, res: Response): - Promise { + private async getResponseData( + opts: GaxiosOptions, res: Response|NodeFetchResponse): Promise { switch (opts.responseType) { case 'stream': return res.body; @@ -199,8 +200,9 @@ export class Gaxios { return obj instanceof stream.Readable && typeof obj._read === 'function'; } - private translateResponse(opts: GaxiosOptions, res: Response, data?: T): - GaxiosResponse { + private translateResponse( + opts: GaxiosOptions, res: Response|NodeFetchResponse, + data?: T): GaxiosResponse { // headers need to be converted from a map to an obj const headers = {} as Headers; res.headers.forEach((value, key) => {