stolli
stolli

Reputation: 5926

Can an Ember data record be created that doesn't fill in unset properties with undefined or null?

Let's say this is my ember model:

import DS from 'ember-data'

export default DS.Model.extend({
  foo: DS.attr('string'),
  bar: DS.attr(undefined),
  fizz: DS.attr('string'),
  buzz: DS.attr('string')
})

and this is some data I collect from a form:

let data = {
  foo: 'foo_value',
  bar: 'bar_value',
  fizz: 'fizz_value'
}

I then pass that data into a create call:

this.store.create('some_model', data)

Inevitably I end up with an Ember data record that has the property buzz set, as undefined, even though I didn't specify it. Then in mirage, I can see that this becomes the following POST body:

{
  foo: 'foo_value',
  bar: 'bar_value',
  fizz: 'fizz_value',
  buzz: undefined
}

The problem is that my API doesn't like undefined, empty, or otherwise values it considers "unset." I have no control over this.

Can I tell Ember not to set those properties on the model, if I haven't passed them in on the create call?

Upvotes: 0

Views: 57

Answers (1)

Pat Diola
Pat Diola

Reputation: 91

I would use a custom serializer to form the data in the way that the API is expecting.

export default DS.JSONSerializer.extend({
  serialize(snapshot, options) {
    var json = this._super(...arguments);

    delete json.data.attributes.buzz;

    return json;
  }
});

https://guides.emberjs.com/v2.1.0/models/customizing-serializers/

Upvotes: 0

Related Questions