Skip to content

Instantly share code, notes, and snippets.

@tabrindle
Created April 19, 2016 22:16
Show Gist options
  • Save tabrindle/56f0d306b83b9d3bac1b47c1757150a7 to your computer and use it in GitHub Desktop.
Save tabrindle/56f0d306b83b9d3bac1b47c1757150a7 to your computer and use it in GitHub Desktop.
Client side config object for web apps
(function() {
const fetchJSON = function(url) {
return Q.Promise((resolve) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
if (xhr.getResponseHeader('Content-Type') === 'application/json') {
resolve(JSON.parse(xhr.responseText));
}
}
};
xhr.send(null);
});
};
const extend = function(target) {
for (let i = 1; i < arguments.length; ++i) {
const original = arguments[i];
if (typeof original !== 'object') continue;
for (const j in original) {
if (original.hasOwnProperty(j)) {
target[j] = typeof original[j] === 'object' ? extend({}, target[j], original[j]) : original[j];
}
}
}
return target;
};
fetchJSON('config/default.json')
.then((default_config) => [default_config, fetchJSON('config/config.json')])
.spread((default_config, env_config) => {
window.config = extend({}, default_config, env_config);
})
['catch']((err) => {
console.log(err);
})
.done();
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment