static-cms/src/actions/config.js

94 lines
2.2 KiB
JavaScript
Raw Normal View History

2016-12-23 16:59:48 -02:00
import yaml from "js-yaml";
import { set, defaultsDeep } from "lodash";
import { authenticateUser } from "../actions/auth";
2016-12-23 16:59:48 -02:00
import * as publishModes from "../constants/publishModes";
2016-02-25 00:45:56 -08:00
2016-12-23 16:59:48 -02: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
const defaults = {
publish_mode: publishModes.SIMPLE,
};
export function applyDefaults(config) {
2016-12-23 16:59:48 -02:00
if (!("media_folder" in config)) {
throw new Error("Error in configuration file: A `media_folder` wasn't found. Check your config.yml file.");
}
// Make sure there is a public folder
set(defaults,
2016-12-23 16:59:48 -02:00
"public_folder",
config.media_folder.charAt(0) === "/" ? config.media_folder : `/${ config.media_folder }`);
return defaultsDeep(config, defaults);
}
function parseConfig(data) {
const config = yaml.safeLoad(data);
2016-12-23 16:59:48 -02:00
if (typeof CMS_ENV === "string" && config[CMS_ENV]) {
// TODO: Add tests and refactor
for (const key in config[CMS_ENV]) { // eslint-disable-line no-restricted-syntax
if (config[CMS_ENV].hasOwnProperty(key)) { // eslint-disable-line no-prototype-builtins
config[key] = config[CMS_ENV][key];
}
}
}
return config;
}
2016-02-25 00:45:56 -08:00
export function configLoaded(config) {
return {
type: CONFIG_SUCCESS,
payload: config,
2016-02-25 00:45:56 -08:00
};
}
export function configLoading() {
return {
type: CONFIG_REQUEST,
2016-02-25 00:45:56 -08:00
};
}
export function configFailed(err) {
return {
type: CONFIG_FAILURE,
2016-12-23 16:59:48 -02:00
error: "Error loading config",
payload: err,
2016-02-25 00:45:56 -08:00
};
}
export function configDidLoad(config) {
return (dispatch) => {
dispatch(configLoaded(config));
};
}
export function loadConfig() {
2016-02-25 00:45:56 -08:00
if (window.CMS_CONFIG) {
return configDidLoad(window.CMS_CONFIG);
2016-02-25 00:45:56 -08:00
}
return (dispatch) => {
2016-02-25 00:45:56 -08:00
dispatch(configLoading());
2017-04-14 17:12:13 +01:00
fetch("config.yml", { credentials: 'same-origin' })
.then((response) => {
2016-02-25 00:45:56 -08:00
if (response.status !== 200) {
throw new Error(`Failed to load config.yml (${ response.status })`);
2016-02-25 00:45:56 -08:00
}
2017-04-14 17:12:13 +01:00
return response.text();
})
.then(parseConfig)
.then(applyDefaults)
.then((config) => {
dispatch(configDidLoad(config));
dispatch(authenticateUser());
})
.catch((err) => {
2016-02-25 00:45:56 -08:00
dispatch(configFailed(err));
});
};
}