static-cms/src/actions/config.js

66 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-02-25 00:45:56 -08:00
import yaml from 'js-yaml';
2016-05-30 16:55:32 -07:00
import { currentBackend } from '../backends/backend';
import { authenticate } from '../actions/auth';
2016-02-25 00:45:56 -08:00
export const CONFIG_REQUEST = 'CONFIG_REQUEST';
export const CONFIG_SUCCESS = 'CONFIG_SUCCESS';
export const CONFIG_FAILURE = 'CONFIG_FAILURE';
2016-02-25 00:45:56 -08:00
export function configLoaded(config) {
return {
type: CONFIG_SUCCESS,
2016-02-25 00:45:56 -08:00
payload: config
};
}
export function configLoading() {
return {
type: CONFIG_REQUEST
2016-02-25 00:45:56 -08:00
};
}
export function configFailed(err) {
return {
type: CONFIG_FAILURE,
2016-02-25 00:45:56 -08:00
error: 'Error loading config',
payload: err
};
}
export function loadConfig(config) {
if (window.CMS_CONFIG) {
return configLoaded(window.CMS_CONFIG);
}
return (dispatch, getState) => {
dispatch(configLoading());
fetch('/config.yml').then((response) => {
2016-02-25 00:45:56 -08:00
if (response.status !== 200) {
throw `Failed to load config.yml (${response.status})`;
}
2016-05-30 16:55:32 -07:00
response.text().then(parseConfig).then((config) => {
dispatch(configLoaded(config));
const backend = currentBackend(config);
const user = backend && backend.currentUser();
user && dispatch(authenticate(user));
});
2016-02-25 00:45:56 -08:00
}).catch((err) => {
dispatch(configFailed(err));
});
};
}
function parseConfig(data) {
const config = yaml.safeLoad(data);
if (typeof CMS_ENV === 'string' && config[CMS_ENV]) {
for (var key in config[CMS_ENV]) {
if (config[CMS_ENV].hasOwnProperty(key)) {
config[key] = config[CMS_ENV][key];
}
}
}
return config;
}