All files / src request.js

78.57% Statements 11/14
68.75% Branches 11/16
66.67% Functions 2/3
78.57% Lines 11/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 424x 4x     4x                   156x   78x     78x   78x 14x       78x       78x 77x                    
import baseRequest from './baseRequest'
import sanitize from './sanitize'
 
 
const DEFAULT_REQUEST_CONFIG = {
    headers: {
        'Accept': 'application/json'
    }
}
 
/**
 * Small wrapper around js-utility-belt's request that provides url resolving,
 * default settings, and response handling.
 */
export default function request(url, config = {}, onlyJsonResponse = true) {
    // Load default fetch configuration and remove any falsy query parameters
    const requestConfig = Object.assign({}, DEFAULT_REQUEST_CONFIG, config, {
        query: config.query && sanitize(config.query)
    })
    const apiUrl = url
 
    if (requestConfig.jsonBody) {
        requestConfig.headers = Object.assign({}, requestConfig.headers, {
            'Content-Type': 'application/json'
        })
    }
    Iif (!url) {
        return Promise.reject(new Error('Request was not given a url.'))
    }
 
    return baseRequest(apiUrl, requestConfig)
        .then((res) => onlyJsonResponse ? res.json() : // eslint-disable-line no-confusing-arrow
        {
            json: res.json(),
            url: res.url
        })
        .catch((err) => {
            console.error(err)
            throw err
        })
}