Skip to content

Instantly share code, notes, and snippets.

@jakeonfire
Last active February 10, 2016 19:56
Show Gist options
  • Save jakeonfire/16d71f131567145650b9 to your computer and use it in GitHub Desktop.
Save jakeonfire/16d71f131567145650b9 to your computer and use it in GitHub Desktop.
JSONAPI-inheriting FormData adapter
import Ember from 'ember';
import ApplicationAdapter from './application';
export default ApplicationAdapter.extend({
// only convert to FormData for the following http methods:
methods: ['POST', 'PATCH', 'PUT'],
ajaxOptions(url, type, options) {
let unserializedData = options && options.data;
let hash = this._super(...arguments);
if (unserializedData && this.methods.contains(type)) {
hash.processData = false;
hash.contentType = false;
let formData = new FormData();
let serializeFormData = (keyPath, data) => {
for (let key in data) {
let newKeyPath = `${keyPath}[${key}]`;
let value = data[key];
if (value) {
if (Ember.$.isPlainObject(value)) {
serializeFormData(newKeyPath, value);
} else {
formData.append(newKeyPath, value);
}
}
}
};
let root = Object.keys(unserializedData)[0];
let data = unserializedData[root];
serializeFormData(root, data);
hash.data = formData;
}
return hash;
}
});
@jakeonfire
Copy link
Author

in the rails-server, which uses the jsonapi-resources gem, i had to do some finagling since it breaks the JSON-API format. any actions receiving modified calls need skip_before_action :ensure_correct_media_type and some implementation tweaks. e.g. after manually creating/updating the model instance:

serializer = JSONAPI::ResourceSerializer.new(resource_klass)
model_resource = resource_klass.new(model_instance, nil)
render json: serializer.serialize_to_hash(model_resource)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment