Use adapter in one-off scenario


#1

Hi there.

I have a model which, when created, I want to upload an archive file to the backend, which will process its contents and generate a number of hasMany records for the new record.

I figure the best way to handle the situation is to serialize the new form into a FormData object, and send it like that. The archives are way too big to encode into base64.

The file, after being uploaded, doesn’t need to be persisted with the record, and the model will never need to know about it again. Its only purpose is to let the backend populate a hasMany association.

That being said, I’d prefer to use a standard ActiveModel{Adapter,Serializer} most of the time, and a custom {Adapter,Serializer} only for creating new records. Is this possible?

Thanks.


#2

For what it’s worth, I used a custom adapter and overrode createRecord to post multipart form data:

export default ApplicationAdapter.extend({
  createRecord: function (store, type, record) {
    var serializedIssue = record.serialize()
      , formData = new FormData()
      , $ = Ember.$
      , that = this

    Ember.keys(serializedIssue).forEach(function (key) {
      formData.append('issue[%@]'.fmt(key), serializedIssue[key])
    })

    formData.append('issue[file]', record.get('file'))

    return new Ember.RSVP.Promise(function (resolve, reject) {
      $.ajax({
        contentType: false,
        data: formData,
        processData: false,
        type: 'POST',
        url: 'http://localhost:3000/issues'
      }).done(function (json) {
        resolve(json)
      }).fail(function(jqXHR, textStatus, error) {
        reject(error)
      })
    })
  }
});

For the moment the rails backend creates all the child records synchronously and replies with the IDs embedded in the new record.

Eventually I’ll get those to build in a worker process and then use a side channel to signal the updates to the frontend. But I’ll care about that when I actually have something worth deploying :smile: