From 5a13eabceb2d3ec2776ccf541821adca71e9c484 Mon Sep 17 00:00:00 2001 From: William Swanson Date: Fri, 11 Oct 2019 11:25:14 -0700 Subject: [PATCH] Accept a `fetch` option for dependency injection Edge Wallet runs in a WebView, which has CORS limitations. We can get around this by bridging the React Native `fetch` method into the WebView, but we need some way to inject this method into this library. --- README.md | 8 ++++++++ src/apigen.js | 7 ++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9617c67..364995f 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,14 @@ fetch('https://example.com', { }) ``` +### options.fetch + +```js +options.fetch = window.fetch +``` + +It is possible to pass an `options.fetch` function, which this library will use in place of the browser's `fetch` method. This may be useful for unit-testing. + ## Environment Node and browser (es2015) diff --git a/src/apigen.js b/src/apigen.js index 9fa6394..baa687a 100644 --- a/src/apigen.js +++ b/src/apigen.js @@ -70,7 +70,12 @@ function fetchMethod (methodName, url, definition, config) { const fetchConfiguration = {body, method: 'POST'} Object.assign(fetchConfiguration, config.fetchConfiguration) - fetch(url, fetchConfiguration).then(response => { + // We have to use the naked `fetch` on Safari (or `this` will be wrong), + // unless the config has provided one to use instead: + const promise = config.fetch != null + ? config.fetch(url, fetchConfiguration) + : fetch(url, fetchConfiguration) + promise.then(response => { if (response.status >= 200 && response.status < 300) { return response.json() } else {