Transforms
In Ember Data, attr defines an attribute on a Model. By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: string, number, boolean and date.
You can define your own transforms by subclassing Transform. Ember Data transforms are normal TypeScript classes. The return type of deserialize method becomes type of the model class property.
You may define your own transforms in TypeScript like so:
1
# app/transforms/coordinate-point.ts
2
import Transform from '@ember-data/serializer/transform';
3
4
declare module 'ember-data/types/registries/transform' {
5
export default interface TransformRegistry {
6
'coordinate-point': CoordinatePointTransform;
7
}
8
}
9
10
export type CoordinatePoint = {
11
x: number;
12
y: number;
13
};
14
15
export default class CoordinatePointTransform extends Transform {
16
deserialize(serialized): CoordinatePoint {
17
return { x: value[0], y: value[1] };
18
}
19
20
serialize(value): number {
21
return [value.x, value.y];
22
}
23
}
24
25
# app/models/cursor.ts
26
import Model, { attr } from '@ember-data/model';
27
import { CoordinatePoint } from 'agwa-data/transforms/coordinate-point';
28
29
declare module 'ember-data/types/registries/transform' {
30
export default interface ModelRegistry {
31
cursor: Cursor;
32
}
33
}
34
35
export default class Cursor extends Model {
36
@attr('coordinate-point') declare position: CoordinatePoint;
37
}
Copied!
Note that you should declare your own transform under TransformRegistry to make attr to work with your transform.
Last modified 2mo ago
Export as PDF
Copy link
Edit on GitHub