Class Transform

public

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

app/transforms/temperature.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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

app/models/requirement.js
1
2
3
4
5
6
7
8
9
10
11
import Model, { attr } from '@ember-data/model';

export default class RequirementModel extends Model {
  @attr('markdown', {
    markdown: {
      gfm: false,
      sanitize: true
    }
  })
  markdown;
}
app/transforms/markdown.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
  }
}

Show:

serialized
The serialized value
options
hash of options passed to `attr`
returns
The deserialized value

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

Example

1
2
3
deserialize(serialized, options) {
  return empty(serialized) ? null : Number(serialized);
}
deserialized
The deserialized value
options
hash of options passed to `attr`
returns
The serialized value

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

Example

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