2424 */
2525
2626var errors = require ( 'web3-core-helpers' ) . errors ;
27+ var fetch = require ( 'cross-fetch' ) ;
2728var http = require ( 'http' ) ;
2829var https = require ( 'https' ) ;
2930
3031// Apply missing polyfill for IE
31- require ( 'cross-fetch/polyfill' ) ;
3232require ( 'es6-promise' ) . polyfill ( ) ;
3333
3434// import abortController if abortController is not included in node
3535if ( typeof global !== "undefined" && ! global . AbortController ) {
36- require ( 'abortcontroller-polyfill/dist/polyfill-patch-fetch' )
36+ require ( 'abortcontroller-polyfill/dist/polyfill-patch-fetch' ) ;
3737}
3838
3939/**
@@ -46,6 +46,7 @@ var HttpProvider = function HttpProvider(host, options) {
4646 this . timeout = options . timeout || 0 ;
4747 this . headers = options . headers ;
4848 this . agent = options . agent ;
49+ this . forceGlobalFetch = options . forceGlobalFetch || false ;
4950 this . connected = false ;
5051
5152 // keepAlive is true unless explicitly set to false
@@ -74,6 +75,7 @@ HttpProvider.prototype.send = function (payload, callback) {
7475 } ;
7576 var headers = { } ;
7677 var controller ;
78+ var fetchFunc = this . forceGlobalFetch ? globalThis . fetch : fetch ;
7779
7880 if ( typeof AbortController !== 'undefined' ) {
7981 controller = new AbortController ( ) ;
@@ -138,11 +140,25 @@ HttpProvider.prototype.send = function (payload, callback) {
138140 }
139141
140142 // Response is a stream data so should be awaited for json response
141- response . json ( ) . then ( function ( data ) {
142- callback ( null , data ) ;
143- } ) . catch ( function ( error ) {
144- callback ( errors . InvalidResponse ( response ) ) ;
145- } ) ;
143+ response
144+ . json ( )
145+ . then (
146+ function ( data ) {
147+ callback ( null , data ) ;
148+ } ,
149+ function ( ) {
150+ response
151+ . text ( )
152+ . then (
153+ function ( text ) {
154+ callback ( errors . InvalidResponse ( text ) ) ;
155+ } ,
156+ function ( ) {
157+ callback ( errors . InvalidResponse ( "" ) ) ;
158+ }
159+ ) ;
160+ }
161+ ) ;
146162 } ;
147163
148164 var failed = function ( error ) {
@@ -152,14 +168,14 @@ HttpProvider.prototype.send = function (payload, callback) {
152168
153169 if ( error . name === 'AbortError' ) {
154170 callback ( errors . ConnectionTimeout ( this . timeout ) ) ;
171+ return ;
155172 }
156173
157174 callback ( errors . InvalidConnection ( this . host , error ) ) ;
158- }
175+ } ;
159176
160- fetch ( this . host , options )
161- . then ( success . bind ( this ) )
162- . catch ( failed . bind ( this ) ) ;
177+ fetchFunc ( this . host , options )
178+ . then ( success . bind ( this ) , failed . bind ( this ) ) ;
163179} ;
164180
165181HttpProvider . prototype . disconnect = function ( ) {
0 commit comments