(apiUrl = '', action)
| 8 | import { buildURL } from './buildURL'; |
| 9 | |
| 10 | export const createFetchFunction = (apiUrl = '', action) => { |
| 11 | // custom handler (should also handle file, load, error, progress and abort) |
| 12 | if (typeof action === 'function') { |
| 13 | return action; |
| 14 | } |
| 15 | |
| 16 | // no action supplied |
| 17 | if (!action || !isString(action.url)) { |
| 18 | return null; |
| 19 | } |
| 20 | |
| 21 | // set onload hanlder |
| 22 | const onload = action.onload || (res => res); |
| 23 | const onerror = action.onerror || (res => null); |
| 24 | |
| 25 | // internal handler |
| 26 | return (url, load, error, progress, abort, headers) => { |
| 27 | |
| 28 | // do local or remote request based on if the url is external |
| 29 | const request = sendRequest(url, buildURL(apiUrl, action.url), { |
| 30 | ...action, |
| 31 | responseType: 'blob' |
| 32 | }); |
| 33 | |
| 34 | request.onload = (xhr) => { |
| 35 | |
| 36 | // get headers |
| 37 | const headers = xhr.getAllResponseHeaders(); |
| 38 | |
| 39 | // get filename |
| 40 | const filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url); |
| 41 | |
| 42 | // create response |
| 43 | load( |
| 44 | createResponse( |
| 45 | 'load', |
| 46 | xhr.status, |
| 47 | action.method === 'HEAD' ? null : getFileFromBlob(onload(xhr.response), filename), |
| 48 | headers |
| 49 | ) |
| 50 | ) |
| 51 | }; |
| 52 | |
| 53 | request.onerror = (xhr) => { |
| 54 | error( |
| 55 | createResponse( |
| 56 | 'error', |
| 57 | xhr.status, |
| 58 | onerror(xhr.response) || xhr.statusText, |
| 59 | xhr.getAllResponseHeaders() |
| 60 | ) |
| 61 | ); |
| 62 | }; |
| 63 | |
| 64 | request.onheaders = (xhr) => { |
| 65 | headers( |
| 66 | createResponse( |
| 67 | 'headers', |
no test coverage detected