js-bigchaindb-driver/src/request.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

2017-06-12 16:57:29 +02:00
import baseRequest from './baseRequest'
import sanitize from './sanitize'
2017-04-26 15:58:19 +02:00
const DEFAULT_REQUEST_CONFIG = {
headers: {
'Accept': 'application/json'
}
2017-06-12 16:57:29 +02:00
}
2017-04-26 15:58:19 +02:00
/**
2017-05-11 17:19:07 +02:00
* Small wrapper around js-utility-belt's request that provides url resolving,
* default settings, and response handling.
2017-04-26 15:58:19 +02:00
*/
2017-06-12 16:57:29 +02:00
export default function request(url, config = {}, onlyJsonResponse = true) {
2017-04-26 15:58:19 +02:00
// Load default fetch configuration and remove any falsy query parameters
const requestConfig = Object.assign({}, DEFAULT_REQUEST_CONFIG, config, {
query: config.query && sanitize(config.query)
2017-06-12 16:57:29 +02:00
})
const apiUrl = url
2017-04-26 15:58:19 +02:00
if (requestConfig.jsonBody) {
requestConfig.headers = Object.assign({}, requestConfig.headers, {
'Content-Type': 'application/json'
2017-06-12 16:57:29 +02:00
})
2017-04-26 15:58:19 +02:00
}
if (!url) {
2017-06-12 16:57:29 +02:00
return Promise.reject(new Error('Request was not given a url.'))
2017-04-26 15:58:19 +02:00
}
return baseRequest(apiUrl, requestConfig)
.then((res) => onlyJsonResponse ? res.json() : // eslint-disable-line no-confusing-arrow
2017-06-12 16:57:29 +02:00
{
json: res.json(),
url: res.url
2017-04-26 15:58:19 +02:00
})
.catch((err) => {
2017-06-12 16:57:29 +02:00
console.error(err)
throw err
})
2017-04-26 15:58:19 +02:00
}