Transforms

Ember Data gives you the ability to transform data from your API to fit the needs of your application. You have already seen in Chapter 21 that Ember Data has built-in transforms – the methods DS.attr('string'), DS.attr('boolean'), DS.attr('number'), and DS.attr('date').

When you add a transform to your application, you can call DS.attr with your target attribute type. Transforms are like JavaScript coercion – they take a value and return the value in a specified type.

Here is an example of a basic DS.attr('object') transform:

export default DS.Transform.extend({
  deserialize(value) {
    if (!Ember.$.isPlainObject(value)) {
      return {};
    } else {
      return value;
    }
  },
  serialize(value) {
    if (!Ember.$.isPlainObject(value)) {
      return {};
    } else {
      return value;
    }
  }
});

The transform has two methods: deserialize and serialize. The first, deserialize, tests whether the incoming data is an object and returns it. Otherwise, it returns an empty object. The second, serialize, returns the outgoing data if it is an object, and otherwise returns an empty object. The transforms guarantee that the data returning from the API and going out to the API are the type defined in the model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.136