Last active
February 10, 2016 19:56
-
-
Save jakeonfire/16d71f131567145650b9 to your computer and use it in GitHub Desktop.
JSONAPI-inheriting FormData adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: