Skip to content

Instantly share code, notes, and snippets.

@SkylerLipthay
Created February 8, 2016 12:50
Show Gist options
  • Save SkylerLipthay/dfa30f831a58dac160f8 to your computer and use it in GitHub Desktop.
Save SkylerLipthay/dfa30f831a58dac160f8 to your computer and use it in GitHub Desktop.
Mithril serialization patch
// Recursively traverses any object or array of objects and converts object
// keys from under_score to camelCase.
function camelize(object) { /* ... */ }
// Recursively traverses any object or array of objects and converts object
// keys from camelCase to under_score.
function underscore(object) { /* ... */ }
// Accepts Mithril's `m` object and Decorates the `m.request` function to
// deserialize using the `camelize` function and to serialize using the
// `underscore` function, unless a `deserialize` or `serialize` option
// respectively is already provided.
//
// The amount of specialization required to decorate Mithril like this makes
// me question if this is the right thing to do.
function patchMithril(m) {
const originalRequest = m.request;
m.request = function(opts) {
const originalConfig = opts.config;
const hasNewDeserialize = !opts.deserialize;
const hasNewSerialize = !opts.serialize;
if (hasNewDeserialize) {
opts.deserialize = function(data) {
return camelize(JSON.parse(data));
};
// This specialization is getting ridiculous!
opts.extract = function(xhr) {
return xhr.responseText || null;
};
}
if (hasNewSerialize) {
opts.serialize = function(data) {
return JSON.stringify(underscore(data));
};
}
opts.config = function(xhr) {
// These XHR headers are applied by Mithril if and only if `deserialize`
// is set to the default `JSON.parse` and `serialize` is set to the
// default `JSON.stringify`. Because we are replacing the default
// serializer and deserializer, we must reimplement this feature.
if (hasNewDeserialize) {
xhr.setRequestHeader('Accept', 'application/json, text/*');
}
if (hasNewSerialize && opts.data && opts.method !== 'GET') {
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
}
if (originalConfig) {
originalConfig(xhr, opts);
}
};
return originalRequest.call(m, opts);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment