Debian Codegraph @

skins/Vector/resources/skins.vector.search/fetch.js

raw symbols SCIP
1 /**
2 * @typedef {Object} AbortableFetch
3 * @property {Promise<any>} fetch
4 * @property {Function} abort
5 */
6
7 /**
8 * @typedef {Object} NullableAbortController
9 * @property {AbortSignal | undefined} signal
10 * @property {Function} abort
11 */
12 const nullAbortController = {
13 signal: undefined,
14 abort: () => {} // Do nothing (no-op)
15 };
16
17 /**
18 * A wrapper which combines native fetch() in browsers and the following json() call.
19 *
20 * @param {string} resource
21 * @param {RequestInit} [init]
22 * @return {AbortableFetch}
23 */
24 function fetchJson( resource, init ) {
25 // As of 2020, browser support for AbortController is limited:
26 // https://caniuse.com/abortcontroller
27 // so replacing it with no-op if it doesn't exist.
28 const controller = window.AbortController ?
29 new AbortController() :
30 nullAbortController;
31
32 const getJson = fetch( resource, Object.assign( {}, init, {
33 signal: controller.signal
34 } ) ).then( ( response ) => {
35 if ( !response.ok ) {
36 return Promise.reject(
37 'Network request failed with HTTP code ' + response.status
38 );
39 }
40 return response.json();
41 } );
42
43 return {
44 fetch: getJson,
45 abort: () => {
46 controller.abort();
47 }
48 };
49 }
50
51 module.exports = fetchJson;