2018-08-07 14:46:54 -06:00
|
|
|
import { get } from 'lodash';
|
|
|
|
import { fromJS } from 'immutable';
|
|
|
|
import { fileExtension } from './path';
|
2018-07-19 18:11:23 -07:00
|
|
|
|
|
|
|
export const filterByPropExtension = (extension, propName) => arr =>
|
|
|
|
arr.filter(el => fileExtension(get(el, propName)) === extension);
|
|
|
|
|
|
|
|
const catchFormatErrors = (format, formatter) => res => {
|
|
|
|
try {
|
|
|
|
return formatter(res);
|
|
|
|
} catch (err) {
|
2018-08-07 14:46:54 -06:00
|
|
|
throw new Error(
|
|
|
|
`Response cannot be parsed into the expected format (${format}): ${err.message}`,
|
|
|
|
);
|
2018-07-19 18:11:23 -07:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const responseFormatters = fromJS({
|
|
|
|
json: async res => {
|
2018-08-07 14:46:54 -06:00
|
|
|
const contentType = res.headers.get('Content-Type');
|
|
|
|
if (!contentType.startsWith('application/json') && !contentType.startsWith('text/json')) {
|
|
|
|
throw new Error(`${contentType} is not a valid JSON Content-Type`);
|
2018-07-19 18:11:23 -07:00
|
|
|
}
|
|
|
|
return res.json();
|
|
|
|
},
|
|
|
|
text: async res => res.text(),
|
|
|
|
blob: async res => res.blob(),
|
2018-08-07 14:46:54 -06:00
|
|
|
}).mapEntries(([format, formatter]) => [format, catchFormatErrors(format, formatter)]);
|
2018-07-19 18:11:23 -07:00
|
|
|
|
2018-08-07 14:46:54 -06:00
|
|
|
export const parseResponse = async (res, { expectingOk = true, format = 'text' } = {}) => {
|
2018-07-19 18:11:23 -07:00
|
|
|
if (expectingOk && !res.ok) {
|
2018-08-07 14:46:54 -06:00
|
|
|
throw new Error(`Expected an ok response, but received an error status: ${res.status}.`);
|
2018-07-19 18:11:23 -07:00
|
|
|
}
|
|
|
|
const formatter = responseFormatters.get(format, false);
|
|
|
|
if (!formatter) {
|
2018-08-07 14:46:54 -06:00
|
|
|
throw new Error(`${format} is not a supported response format.`);
|
2018-07-19 18:11:23 -07:00
|
|
|
}
|
|
|
|
const body = await formatter(res);
|
|
|
|
return body;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const responseParser = options => res => parseResponse(res, options);
|