API Docs for: 5.4.0-alpha.29+64fa97fc
Show:

Transform Class

The Transform class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing Transform is useful for creating custom attributes. All subclasses of Transform must implement a serialize and a deserialize method.

Example


// Converts centigrade in the JSON to fahrenheit in the app
export default class TemperatureTransform {
  deserialize(serialized, options) {
    return (serialized *  1.8) + 32;
  }

  serialize(deserialized, options) {
    return (deserialized - 32) / 1.8;
  }

  static create() {
    return new this();
  }
}

Usage

import Model, { attr } from '@ember-data/model';

export default class RequirementModel extends Model {
  @attr('string') name;
  @attr('temperature') temperature;
}

The options passed into the attr function when the attribute is declared on the model is also available in the transform.

import Model, { attr } from '@ember-data/model';

export default class PostModel extends Model {
  @attr('string') title;
  @attr('markdown', {
    markdown: {
      gfm: false,
      sanitize: true
    }
  })
  markdown;
}
export default class MarkdownTransform {
  serialize(deserialized, options) {
    return deserialized.raw;
  }

  deserialize(serialized, options) {
    let markdownOptions = options.markdown || {};

    return marked(serialized, markdownOptions);
  }

  static create() {
    return new this();
  }
}

Item Index

Methods

deserialize

(
  • serialized
  • options
)
public

When given a serialized value from a JSON object this method must return the deserialized value for the record attribute.

Example

deserialize(serialized, options) {
  return empty(serialized) ? null : Number(serialized);
}

Parameters:

  • serialized Object

    The serialized value

  • options Object

    hash of options passed to attr

Returns:

The deserialized value

serialize

(
  • deserialized
  • options
)
public

When given a deserialized value from a record attribute this method must return the serialized value.

Example

serialize(deserialized, options) {
  return deserialized ? null : Number(deserialized);
}

Parameters:

  • deserialized Object

    The deserialized value

  • options Object

    hash of options passed to attr

Returns:

The serialized value