1
votes

I am using Ember-Data (v1.13.13) to manage objects coming from the server.

The value of an incoming attribute is null. The attribute type is a string with default value being an empty string. The null is not defaulting to the empty string as expected. So it looks like Ember-Data establishes a nullable string data type by default (thinking about it in general terms, not a JavaScript thing, of course).

In any case, I would like to know how to convert the incoming null to the default empty string value as the model is "instantiated". That or indicate to Ember-Data to consider the property in terms of a string type rather than a nullable string type.

The model (simplified):

App.Note = DS.Model.extend({
    mystring: DS.attr('string', { defaultValue: '' })
});

The incoming object:

{
    "notes": [{
        "mystring": null
    }]
}

The resulting value in memory:

<App.Note:ember1133:1775>
mystring: null
2
Default values are typically for new records, not old ones. Deal with the null, imo -- that is 'the truth'. - user2105103
You're probably right. I was using default values to set the initial type of the incoming items. Of course as soon as you edit a bound number it converts to a string anyway. Need to respect the JavaScript variable behavior. Been caught up on the server-side for too long. - edson-

2 Answers

2
votes

Null and empty string are different, so it is not surprising that Ember Data's string transform does not do that conversion. However, you can write your own which does:

// transforms/string-null-to-empty.js
export default DS.Transform.extend({
  deserialize(serialized) { return serialized || ''; },
  serialize(deserialized) { return deserialized; }
});

then

mystring: DS.attr('string-null-to-empty')
1
votes

Overriding the normalize method in your RESTSerializer will also do the trick. Something like this should work

DS.RESTSerializer.extend({
   normalize: function(modelClass, hash, prop) {
     // Do whatever checking you need to to make sure
     // modelClass (or hash.type) is the type you're looking for
     hash.mystring = hash.mystring || '';
     return this._super(modelClass, hash, prop);
   }
 });

Of course, if you don't always know which keys you'll need to normalize from null to an empty string then you could just iterate over all of them (however this will be slower).

DS.RESTSerializer.extend({
   normalize: function(modelClass, hash, prop) {
     Object.keys(hash).forEach(function(key){
       hash[key] = hash[key] || '';
     });
     return this._super(modelClass, hash, prop);
   }
 });