Skip to content

Conversation

pixelhandler
Copy link
Owner

The application serializer has methods for [de]serializing the date values between client and server. An attribute that is setup as a 'date' type also has a built in transform method to serialize and deserialize the date value. Typically the JSON value for a Date object is communicated in ISO format, e.g. "2015-08-25T22:05:37.393Z".

The TransformsMixin defines serializeDateAttribute and deserializeDateAttribute. Any valid type can be added to your app, just generate a transforms mixin and define other types if needed. Or when you generate a resource add the type specific methods or attribute name specific methods on the serializer prototype (class) for your resource.

The methods use a naming convention '[de]serialize' + 'AttrName' or 'TypeName' + 'Attribute'; so to add a specific method to transform a name value for an author resource add two methods:

import ApplicationSerializer from './application';

export default ApplicationSerializer.extend({
  serializeNameAttribute(value) {
    return value.split('written by: ')[1];
  },
  deserializeNameAttribute(value) {
    return 'written by: ' + value;
  },
});

Or, to handle a date type transform differently than the default to/from ISO format transformation:

import ApplicationSerializer from './application';

export default ApplicationSerializer.extend({
  serializeDateAttribute(date) {
    return /* serialized format from your resource attribute value, for use on your API server */;
  },
  deserializeDateAttribute(date) {
    return /* deserialized format from your API server, for use in your client app*/;
  },
});

You can add your own transform methods based on the type of the attribute or based on the name of the attribute, the transform methods based on the name of the attribute will be called instead of any transform methods based on the type of the attribute.

@pixelhandler pixelhandler force-pushed the transform-attributes branch 2 times, most recently from f058ef7 to 863d0c9 Compare August 25, 2015 23:37
pixelhandler added a commit that referenced this pull request Aug 25, 2015
Add transform methods for [de]serializing resource attributes
@pixelhandler pixelhandler merged commit b52811e into master Aug 25, 2015
@pixelhandler pixelhandler deleted the transform-attributes branch August 25, 2015 23:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant