Skip to content

Commit

Permalink
own function for fetch of config
Browse files Browse the repository at this point in the history
  • Loading branch information
talves authored and erquhart committed Mar 28, 2018
1 parent 1ded55a commit c38a887
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions src/actions/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ export function validateConfig(config) {
return config;
}

function mergePreloadedConfig(preloadedConfig, fetchedConfig) {
const map = fromJS(fetchedConfig) || Map();
function mergePreloadedConfig(preloadedConfig, loadedConfig) {
const map = fromJS(loadedConfig) || Map();
return preloadedConfig ? preloadedConfig.mergeDeep(map) : map;
}

Expand All @@ -75,12 +75,20 @@ function parseConfig(data) {
return config;
}

async function getConfigFromResponse(response) {
const { status, headers } = response;
if (status === 200 && !headers.get('Content-Type').includes('text/html')) {
const config = await response.text();
return parseConfig(config);
async function getConfig(file, isPreloaded) {
const response = await fetch(file, { credentials: 'same-origin' });
if (response.status !== 200) {
if (isPreloaded) return parseConfig('');
throw new Error(`Failed to load config.yml (${ response.status })`);
}
const contentType = response.headers.get('Content-Type') || 'Not-Found';
const isYaml = contentType.indexOf('yaml') !== -1;
if (!isYaml) {
console.log(`Response for ${ file } was not yaml. (Content-Type: ${ contentType })`);
if (isPreloaded) return parseConfig('');
throw new Error('Failed to load configuration.');
}
return parseConfig(await response.text());
}

export function configLoaded(config) {
Expand Down Expand Up @@ -123,17 +131,12 @@ export function loadConfig() {

try {
const preloadedConfig = getState().config;
const response = await fetch('config.yml', { credentials: 'same-origin' })
const fetchedConfig = await getConfigFromResponse(response);

if (!preloadedConfig && !fetchedConfig) {
throw new Error(`Failed to load configuration.`);
}
const loadedConfig = await getConfig('config.yml', preloadedConfig && preloadedConfig.size > 1);

/**
* Merge any existing configuration so the result can be validated.
*/
const mergedConfig = mergePreloadedConfig(preloadedConfig, fetchedConfig)
const mergedConfig = mergePreloadedConfig(preloadedConfig, loadedConfig);
const config = flow(validateConfig, applyDefaults)(mergedConfig);

dispatch(configDidLoad(config));
Expand Down

0 comments on commit c38a887

Please sign in to comment.