@selkirk-systems/fetch 0.1.6 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,61 +1,17 @@
1
- # Selkirk Fetch
1
+ # `Fetch`
2
2
 
3
- This is a wrapper for [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch).
4
- All options provided by isomorphic-fetch are available by default.
3
+ Abortable Fetch Library
5
4
 
6
-
7
- ### Notes
8
- This wrapper abstracts some additional config that selkirk would use 90% of the time.
9
- All config options can be overridden if needed
10
-
11
- Config
12
- - All Data sent and received assumed to be JSON
13
- - Anything set to the body property is automatically JSON.stringify
14
- - Method "GET" is assumed if not provided
15
- - Responses from the server are processed into JSON objects automatically.
16
- - Errors in responses are also processed and will cause a "catch" to fire based on httpResponseCodes
17
-
18
-
19
- ### Component Example
20
-
21
- ```
22
- const Fetch = require('selkirk-fetch');
23
-
24
- Fetch('/api', {
25
- method: 'put',
26
- body : user
27
- })
28
- .then((response)=> {
29
- //response is already processed into a valid obj and can be used as such
30
-
31
- Dispatcher.handleViewAction({
32
- actionType: Constants.USER_SUBMITTED,
33
- item : response
34
- })
35
- })
36
- .catch((err)=> {
37
- //valid httpResponseCodes that are considered errors will trigger a catch (500,401) etc.
38
-
39
- _onError(err);
40
- Dispatcher.handleViewAction({
41
- actionType: Constants.USER_SUBMIT_FAILED,
42
- })
43
- })
5
+ ## Usage
44
6
 
45
7
  ```
8
+ import { Fetch } from "@selkirk-systems/fetch";
46
9
 
47
- #### Boilerplate
48
-
49
- The package is based on [react-npm-boilerplate](https://github.com/juliancwirko/react-npm-boilerplate). This one is prepared to be used as a starter point for React components which needs to be published on Npm.
10
+ export const fetchAgreementsByFiscalYear = ( year ) => {
50
11
 
51
- It includes linting with [ESLint](http://eslint.org/) and testing with [Mocha](https://mochajs.org/), [Enzyme](http://airbnb.io/enzyme/) and [JSDOM](https://github.com/tmpvar/jsdom).
12
+ dispatch( FETCH_AGREEMENTS );
52
13
 
53
- Also there is of course ES6 transpilation.
14
+ return Fetch( AGREEMENTS_LOOKUP_BY_FISCAL_YEAR_URL( { fiscalYear: year } ) ).then( respondWith( FETCHED_AGREEMENTS ) );
54
15
 
55
- #### Basic Usage
56
-
57
- 1. Clone this repo
58
- 2. Inside cloned repo run `npm install`
59
- 3. If you want to run tests: `npm test` or `npm run testonly` or `npm run test-watch`. You need to write tests in `__tests__` folder. You need at least Node 4 on your machine to run tests.
60
- 4. If you want to run linting: `npm test` or `npm run lint`. Fix bugs: `npm run lint-fix`. You can adjust your `.eslintrc` config file.
61
- 5. If you want to run transpilation to ES5 in `dist` folder: `npm run prepublish` (standard npm hook).
16
+ }
17
+ ```
@@ -0,0 +1,183 @@
1
+ /* eslint-disable */
2
+
3
+ //download.js v4.21, by dandavis; 2008-2018. [MIT] see http://danml.com/download.html for tests/usage
4
+ // v1 landed a FF+Chrome compatible way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
5
+ // v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
6
+ // v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
7
+ // v4 adds AMD/UMD, commonJS, and plain browser support
8
+ // v4.1 adds url download capability via solo URL argument (same domain/CORS only)
9
+ // v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
10
+ // https://github.com/rndme/download
11
+
12
+ (function (root, factory) {
13
+ if (typeof define === 'function' && define.amd) {
14
+ // AMD. Register as an anonymous module.
15
+ define([], factory);
16
+ } else if (typeof exports === 'object') {
17
+ // Node. Does not work with strict CommonJS, but
18
+ // only CommonJS-like environments that support module.exports,
19
+ // like Node.
20
+ module.exports = factory();
21
+ } else {
22
+ // Browser globals (root is window)
23
+ root.download = factory();
24
+ }
25
+ })(this, function () {
26
+ return function download(data, strFileName, strMimeType) {
27
+ var self = window,
28
+ // this script is only for browsers anyway...
29
+ defaultMime = "application/octet-stream",
30
+ // this default mime also triggers iframe downloads
31
+ mimeType = strMimeType || defaultMime,
32
+ payload = data,
33
+ url = !strFileName && !strMimeType && payload,
34
+ anchor = document.createElement("a"),
35
+ toString = function (a) {
36
+ return String(a);
37
+ },
38
+ myBlob = self.Blob || self.MozBlob || self.WebKitBlob || toString,
39
+ fileName = strFileName || "download",
40
+ blob,
41
+ reader;
42
+ myBlob = myBlob.call ? myBlob.bind(self) : Blob;
43
+ if (String(this) === "true") {
44
+ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
45
+ payload = [payload, mimeType];
46
+ mimeType = payload[0];
47
+ payload = payload[1];
48
+ }
49
+ if (url && url.length < 2048) {
50
+ // if no filename and no mime, assume a url was passed as the only argument
51
+ fileName = url.split("/").pop().split("?")[0];
52
+ anchor.href = url; // assign href prop to temp anchor
53
+ if (anchor.href.indexOf(url) !== -1) {
54
+ // if the browser determines that it's a potentially valid url path:
55
+ var ajax = new XMLHttpRequest();
56
+ ajax.open("GET", url, true);
57
+ ajax.responseType = 'blob';
58
+ ajax.onload = function (e) {
59
+ download(e.target.response, fileName, defaultMime);
60
+ };
61
+ setTimeout(function () {
62
+ ajax.send();
63
+ }, 0); // allows setting custom ajax headers using the return:
64
+ return ajax;
65
+ } // end if valid url?
66
+ } // end if url?
67
+
68
+ //go ahead and download dataURLs right away
69
+ if (/^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(payload)) {
70
+ if (payload.length > 1024 * 1024 * 1.999 && myBlob !== toString) {
71
+ payload = dataUrlToBlob(payload);
72
+ mimeType = payload.type || defaultMime;
73
+ } else {
74
+ return navigator.msSaveBlob ?
75
+ // IE10 can't do a[download], only Blobs:
76
+ navigator.msSaveBlob(dataUrlToBlob(payload), fileName) : saver(payload); // everyone else can save dataURLs un-processed
77
+ }
78
+ } else {
79
+ //not data url, is it a string with special needs?
80
+ if (/([\x80-\xff])/.test(payload)) {
81
+ var i = 0,
82
+ tempUiArr = new Uint8Array(payload.length),
83
+ mx = tempUiArr.length;
84
+ for (i; i < mx; ++i) tempUiArr[i] = payload.charCodeAt(i);
85
+ payload = new myBlob([tempUiArr], {
86
+ type: mimeType
87
+ });
88
+ }
89
+ }
90
+ blob = payload instanceof myBlob ? payload : new myBlob([payload], {
91
+ type: mimeType
92
+ });
93
+ function dataUrlToBlob(strUrl) {
94
+ var parts = strUrl.split(/[:;,]/),
95
+ type = parts[1],
96
+ indexDecoder = strUrl.indexOf("charset") > 0 ? 3 : 2,
97
+ decoder = parts[indexDecoder] == "base64" ? atob : decodeURIComponent,
98
+ binData = decoder(parts.pop()),
99
+ mx = binData.length,
100
+ i = 0,
101
+ uiArr = new Uint8Array(mx);
102
+ for (i; i < mx; ++i) uiArr[i] = binData.charCodeAt(i);
103
+ return new myBlob([uiArr], {
104
+ type: type
105
+ });
106
+ }
107
+ function saver(url, winMode) {
108
+ if ('download' in anchor) {
109
+ //html5 A[download]
110
+ anchor.href = url;
111
+ anchor.setAttribute("download", fileName);
112
+ anchor.className = "download-js-link";
113
+ anchor.innerHTML = "downloading...";
114
+ anchor.style.display = "none";
115
+ anchor.addEventListener('click', function (e) {
116
+ e.stopPropagation();
117
+ this.removeEventListener('click', arguments.callee);
118
+ });
119
+ document.body.appendChild(anchor);
120
+ setTimeout(function () {
121
+ anchor.click();
122
+ document.body.removeChild(anchor);
123
+ if (winMode === true) {
124
+ setTimeout(function () {
125
+ self.URL.revokeObjectURL(anchor.href);
126
+ }, 250);
127
+ }
128
+ }, 66);
129
+ return true;
130
+ }
131
+
132
+ // handle non-a[download] safari as best we can:
133
+ if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
134
+ if (/^data:/.test(url)) url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
135
+ if (!window.open(url)) {
136
+ // popup blocked, offer direct download:
137
+ if (confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")) {
138
+ location.href = url;
139
+ }
140
+ }
141
+ return true;
142
+ }
143
+
144
+ //do iframe dataURL download (old ch+FF):
145
+ var f = document.createElement("iframe");
146
+ document.body.appendChild(f);
147
+ if (!winMode && /^data:/.test(url)) {
148
+ // force a mime that will download:
149
+ url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
150
+ }
151
+ f.src = url;
152
+ setTimeout(function () {
153
+ document.body.removeChild(f);
154
+ }, 333);
155
+ } //end saver
156
+
157
+ if (navigator.msSaveBlob) {
158
+ // IE10+ : (has Blob, but not a[download] or URL)
159
+ return navigator.msSaveBlob(blob, fileName);
160
+ }
161
+ if (self.URL) {
162
+ // simple fast and modern way using Blob and URL:
163
+ saver(self.URL.createObjectURL(blob), true);
164
+ } else {
165
+ // handle non-Blob()+non-URL browsers:
166
+ if (typeof blob === "string" || blob.constructor === toString) {
167
+ try {
168
+ return saver("data:" + mimeType + ";base64," + self.btoa(blob));
169
+ } catch (y) {
170
+ return saver("data:" + mimeType + "," + encodeURIComponent(blob));
171
+ }
172
+ }
173
+
174
+ // Blob but not URL support:
175
+ reader = new FileReader();
176
+ reader.onload = function (e) {
177
+ saver(this.result);
178
+ };
179
+ reader.readAsDataURL(blob);
180
+ }
181
+ return true;
182
+ }; /* end download() */
183
+ });
@@ -0,0 +1,389 @@
1
+ //Inspired by https://www.bennadel.com/blog/4180-canceling-api-requests-using-fetch-and-abortcontroller-in-javascript.htm
2
+
3
+ import Download from './Download';
4
+ import FetchErrorHandler from './middleware/FetchErrorHandler';
5
+
6
+ // Regular expression patterns for testing content-type response headers.
7
+ const RE_CONTENT_TYPE_JSON = /^application\/(x-)?json/i;
8
+ const RE_CONTENT_TYPE_TEXT = /"^text\/"/i;
9
+ const RE_QUERY_STRING = /\/.+\?/;
10
+ const UNEXPECTED_ERROR_MESSAGE = "An unexpected error occurred while processing your request.";
11
+ const CONTENT_TYPE_DOWNLOADS = {
12
+ 'application/pdf': true,
13
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true
14
+ };
15
+ //We store the original promise.catch so we can override it in some
16
+ //scenarios when we want to swallow errors vs bubble them up.
17
+ const ORIGINAL_CATCH_FN = Promise.prototype.catch;
18
+
19
+ //Auto applied middleware that dispatches all errors so any UI's can respond.
20
+ let _middlewares = [FetchErrorHandler];
21
+
22
+ //Cache of request AbortController signals for auto request aborting.
23
+ let _requests = {};
24
+
25
+ /**
26
+ * PUBLIC: Apply custom middleware to act on any fetch responses and errors.
27
+ *
28
+ * NOTE: Middleware can handle errors and swallow them by passing back a new error object.
29
+ *
30
+ * @param {array} middleware
31
+ */
32
+ export function applyMiddleware(middleware = []) {
33
+ _middlewares = middleware;
34
+ _middlewares.push(FetchErrorHandler);
35
+ }
36
+
37
+ /**
38
+ * Make the fetch request with the given configuration options.
39
+ *
40
+ * GUARANTEE: All errors produced by this method will have consistent structure, even
41
+ * if they are low-level networking errors. At a minimum, every Promise rejection will
42
+ * have the following properties:
43
+ *
44
+ * TODO: Add support for multi-form uploads (images, files etc)
45
+ *
46
+ * - data.type
47
+ * - data.message
48
+ * - status.code
49
+ * - status.text
50
+ * - status.isAbort
51
+ */
52
+ export default function Fetch(url, options = {}) {
53
+ const config = {
54
+ downloadFileName: null,
55
+ contentType: "application/json",
56
+ headers: {
57
+ accept: "*/*"
58
+ },
59
+ credentials: "same-origin",
60
+ url: url || "",
61
+ urlTemplateData: {},
62
+ method: "GET",
63
+ params: {},
64
+ form: null,
65
+ json: null,
66
+ body: null,
67
+ signal: new AbortController(),
68
+ ...options,
69
+ _hasCatch: false,
70
+ _promiseChain: null,
71
+ _userSignal: Boolean(options.signal)
72
+ };
73
+ let finalHeaders, finalMethod, finalUrl, finalBody, finalSignal, request;
74
+ try {
75
+ finalHeaders = buildHeaders(config.headers);
76
+ finalMethod = config.method;
77
+ finalUrl = buildURL(config.url, config.urlTemplateData, config.params);
78
+ finalBody = config.body;
79
+ finalSignal = config.signal;
80
+
81
+ // Bail out early if url contains url params,
82
+ //these should be set via the options.params object.
83
+ if (!config.url.href && RE_QUERY_STRING.test(config.url)) {
84
+ return Promise.reject(normalizeError({
85
+ type: "INVALID_URL",
86
+ message: `${config.url} contains query parameters: please use options.params object for this purpose.`
87
+ }, {}, {}, config));
88
+ }
89
+ if (CONTENT_TYPE_DOWNLOADS[config.contentType] && finalMethod === "GET") {
90
+ finalHeaders.credentials = "same-origin";
91
+ finalHeaders.accept = "*/*";
92
+ }
93
+ if (config.form) {
94
+ // For form data posts, we want the browser to build the Content-
95
+ // Type for us so that it puts in both the "multipart/form-data" plus the
96
+ // correct, auto-generated field delimiter.
97
+ delete finalHeaders["content-type"];
98
+ finalMethod = "POST";
99
+ finalBody = buildFormData(config.form);
100
+ } else if (config.json) {
101
+ finalHeaders["content-type"] = config.contentType || "application/x-json";
102
+ finalBody = JSON.stringify(config.json);
103
+ } else if (config.body) {
104
+ finalHeaders["content-type"] = config.contentType || "application/octet-stream";
105
+ } else {
106
+ finalHeaders["content-type"] = config.contentType;
107
+ }
108
+ request = new window.Request(finalUrl, {
109
+ headers: finalHeaders,
110
+ method: finalMethod,
111
+ body: finalBody,
112
+ signal: finalSignal.signal
113
+ });
114
+
115
+ //Check if a pending request is in-flight, if so and it is the exact same url abort it.
116
+ if (_requests[finalUrl]) {
117
+ _requests[finalUrl].abort();
118
+ }
119
+
120
+ //Cache requests abort signal by url
121
+ cacheRequestSignal(finalUrl, finalSignal);
122
+ config._promiseChain = Promise.resolve(window.fetch(request)).then(async response => {
123
+ deleteCachedRequestSignal(finalUrl);
124
+ const data = await unwrapResponseData(response);
125
+ if (response.ok) {
126
+ //Run response through middleware
127
+ const nextResp = _applyMiddleware(null, response, config);
128
+ if (config.downloadFileName) {
129
+ presetBrowserDownloadDialog(data, config);
130
+ }
131
+ return [{
132
+ request: request,
133
+ response: nextResp || response,
134
+ data: data
135
+ }, false];
136
+ }
137
+ return handleError(normalizeError(data, request, response, config), config);
138
+ }).catch(err => {
139
+ deleteCachedRequestSignal(finalUrl);
140
+ const error = isNormalizedError(err) ? err : normalizeTransportError(err);
141
+ return handleError(error, config);
142
+ });
143
+ } catch (err) {
144
+ deleteCachedRequestSignal(finalUrl);
145
+ return handleError(normalizeTransportError(err), config);
146
+ }
147
+ if (config._promiseChain) {
148
+ //If catch is added outside, then assume they want to handle errors and
149
+ //not have them swallowed
150
+
151
+ config._promiseChain.catch = function (...args) {
152
+ config._hasCatch = true;
153
+ return ORIGINAL_CATCH_FN.apply(this, args);
154
+ };
155
+ }
156
+ return config._promiseChain;
157
+ }
158
+
159
+ /**
160
+ * Shows the browser download dialog
161
+ * @param {response.blob} blob
162
+ * @param {object} config
163
+ * @returns
164
+ */
165
+ function presetBrowserDownloadDialog(blob, config) {
166
+ return Download(blob, config.downloadFileName, config.contentType);
167
+ }
168
+
169
+ /**
170
+ * Stores a ref to the abort signal
171
+ * @param {string} url
172
+ * @param {AbortController.signal} signal
173
+ */
174
+ function cacheRequestSignal(url, signal) {
175
+ _requests[url] = signal;
176
+ }
177
+
178
+ /**
179
+ * Deletes a req from the cached requests
180
+ * @param {string} url
181
+ */
182
+ function deleteCachedRequestSignal(url) {
183
+ delete _requests[url];
184
+ }
185
+
186
+ /**
187
+ * Checks if the error structure mimics ours and has already been normalized.
188
+ * @param {Object} err
189
+ * @returns
190
+ */
191
+ function isNormalizedError(err) {
192
+ return err.hasOwnProperty("status") && err.hasOwnProperty("data");
193
+ }
194
+
195
+ /**
196
+ * Handles errors by passing them through any middleware and finally throwing them or swallowing them.
197
+ * @param {object} normalizedError
198
+ * @param {object} config
199
+ * @returns
200
+ */
201
+ function handleError(normalizedError, config) {
202
+ const hasCatch = config._hasCatch;
203
+ const promiseChain = config._promiseChain;
204
+ const nextErr = _applyMiddleware(normalizedError, null, config);
205
+
206
+ //Only swallow errors if they have been handled by middleware AND they have not
207
+ //Added a catch outside
208
+ if (!hasCatch && !nextErr) {
209
+ if (promiseChain && promiseChain.cancel) promiseChain.cancel();
210
+ //In the case of aborted requests etc, we treat them as success and let the initial fetch chain
211
+ //handle them.
212
+ return Promise.resolve([normalizedError, true]);
213
+ }
214
+
215
+ // The request failed in a critical way; the content of this error will be
216
+ // entirely unpredictable.
217
+ return Promise.reject(nextErr || normalizedError);
218
+ }
219
+
220
+ /**
221
+ * Passes any errors, responses through configured middleware
222
+ *
223
+ * @param {ErrorEvent} err the error.
224
+ * @param {Object} response the network response.
225
+ * @param {Object} options the request options.
226
+ * @returns null
227
+ */
228
+ function _applyMiddleware(err, response, options) {
229
+ let i = -1;
230
+ const next = function (nextErr, nextState) {
231
+ i++;
232
+ const middleware = _middlewares[i];
233
+ if (!middleware) return nextErr || nextState;
234
+ return middleware(nextErr)(nextState)(options)(next);
235
+ };
236
+ return next(err, response);
237
+ }
238
+
239
+ /**
240
+ * Unwrap the response payload from the given response based on the reported
241
+ * content-type.
242
+ */
243
+ async function unwrapResponseData(response) {
244
+ var contentType = response.headers.has("content-type") ? response.headers.get("content-type") : "";
245
+ if (RE_CONTENT_TYPE_JSON.test(contentType)) {
246
+ return response.json();
247
+ } else if (RE_CONTENT_TYPE_TEXT.test(contentType)) {
248
+ return response.text();
249
+ } else {
250
+ return response.blob();
251
+ }
252
+ }
253
+
254
+ /**
255
+ * FormData instance from the given object.
256
+ *
257
+ * NOTE: At this time, only simple values (ie, no files) are supported.
258
+ */
259
+ function buildFormData(form) {
260
+ var formData = new FormData();
261
+ Object.entries(form).forEach(([key, value]) => {
262
+ formData.append(key, value);
263
+ });
264
+ return formData;
265
+ }
266
+
267
+ /**
268
+ * Supports url or url with template identifiers,creates a url with optional query parameters.
269
+ * @param {string} url
270
+ * @param {object} templateData
271
+ * @param {object} params
272
+ * @returns
273
+ */
274
+ function buildURL(url, templateData, params) {
275
+ if (url.href) return url;
276
+ const formattedUrl = buildURLTemplate(url, templateData);
277
+ const finalUrl = new URL(formattedUrl, `${window.location.origin}${window.baseUrl || ""}`);
278
+ const searchParams = new URLSearchParams();
279
+ Object.entries(params).forEach(([key, value]) => {
280
+ if (Array.isArray(value)) {
281
+ for (let i = 0; i < value.length; i++) {
282
+ const e = value[i];
283
+ searchParams.append(key, e);
284
+ }
285
+ return;
286
+ }
287
+ searchParams.append(key, value);
288
+ });
289
+ finalUrl.search = searchParams;
290
+ return finalUrl;
291
+ }
292
+
293
+ /**
294
+ * Builds a urls tring using template identifiers.
295
+ * @param {string} url
296
+ * @param {object} templateData
297
+ */
298
+ function buildURLTemplate(url, templateData) {
299
+ Object.entries(templateData).forEach(([key, value]) => {
300
+ url = url.replace(new RegExp(`{${key}}`, "ig"), value.toString());
301
+ });
302
+ return url;
303
+ }
304
+
305
+ /**
306
+ * Transform the collection of HTTP headers into a like collection wherein the names
307
+ * of the headers have been lower-cased. This way, if we need to manipulate the
308
+ * collection prior to transport, we'll know what key-casing to use.
309
+ */
310
+ function buildHeaders(headers) {
311
+ var lowercaseHeaders = {};
312
+ Object.entries(headers).forEach(([key, value]) => {
313
+ lowercaseHeaders[key.toLowerCase()] = value;
314
+ });
315
+ return lowercaseHeaders;
316
+ }
317
+
318
+ /**
319
+ * At a minimum, we want every error to have the following properties:
320
+ *
321
+ * - data.type
322
+ * - data.message
323
+ * - status.code
324
+ * - status.text
325
+ * - status.isAbort
326
+ *
327
+ * These are the keys that the calling context will depend on; and, are the minimum
328
+ * keys that the server is expected to return when it throws domain errors.
329
+ */
330
+ function normalizeError(data, request, response, config) {
331
+ var error = {
332
+ data: {
333
+ type: "ServerError",
334
+ message: UNEXPECTED_ERROR_MESSAGE
335
+ },
336
+ status: {
337
+ code: response.status,
338
+ text: response.statusText,
339
+ isAbort: false
340
+ },
341
+ // The following data is being provided to make debugging AJAX errors easier.
342
+ request: request,
343
+ response: response,
344
+ config: config || {}
345
+ };
346
+
347
+ // If the error data is an Object (which it should be if the server responded
348
+ // with a domain-based error), then it should have "type" and "message"
349
+ // properties within it. That said, just because this isn't a transport error, it
350
+ // doesn't mean that this error is actually being returned by our application.
351
+ if (typeof data?.type === "string" && typeof data?.message === "string") {
352
+ Object.assign(error.data, data);
353
+
354
+ // If the error data has any other shape, it means that an unexpected error
355
+ // occurred on the server (or somewhere in transit). Let's pass that raw error
356
+ // through as the rootCause, using the default error structure.
357
+ } else {
358
+ error.data.rootCause = data;
359
+ }
360
+ return error;
361
+ }
362
+
363
+ /**
364
+ * If our request never makes it to the server (or the round-trip is interrupted
365
+ * somehow), we still want the error response to have a consistent structure with the
366
+ * application errors returned by the server. At a minimum, we want every error to
367
+ * have the following properties:
368
+ *
369
+ * - data.type
370
+ * - data.message
371
+ * - status.code
372
+ * - status.text
373
+ * - status.isAbort
374
+ */
375
+ function normalizeTransportError(transportError) {
376
+ const isAbort = transportError.name === "AbortError";
377
+ return {
378
+ data: {
379
+ type: "TransportError",
380
+ message: isAbort ? "Network Request Aborted" : UNEXPECTED_ERROR_MESSAGE,
381
+ rootCause: transportError
382
+ },
383
+ status: {
384
+ code: 0,
385
+ text: "Unknown",
386
+ isAbort: isAbort
387
+ }
388
+ };
389
+ }
@@ -0,0 +1 @@
1
+ export const ADD_ERROR = "ADD_ERROR";
@@ -0,0 +1 @@
1
+ declare module '@selkirk-systems/fetch';