Skip to content

Ember Data Deprecate Transforms - #343

Closed
Alonski wants to merge 1 commit into
emberjs:masterfrom
Alonski:ember-data-deprecate-transforms
Closed

Alonski wants to merge 1 commit into
emberjs:masterfrom
Alonski:ember-data-deprecate-transforms

Conversation

@Alonski

@Alonski Alonski commented Jun 26, 2018

Copy link
Copy Markdown
Member

@mydea

mydea commented Jun 26, 2018

Copy link
Copy Markdown

We do use transforms quite a lot in our apps, and I don't really see how it would be easy to move this to serializers. Sure, it would be possible, but would be much more verbose. Some examples:

Our server can sometimes return null for array fields, so we have an array transform that ensures we end up with an empty array instead. We use this in multiple different models, and would have to add serializers for all of them.

Then, we also have some common objects, which the server sends as inlined JSON objects, and we convert to actual class instances in transforms (and back to JSON when serializing). Again, this is used many times, and could theoretically be done in a serializer, but would be much more verbose. Currently, we only have special serializers for really custom, one-off functionality, and all generic functionality that we need multiple times in different models can be handled in transforms. Removing transforms and requiring to do all of this in serializers seems very un-DRY to me. It would also mean that we'd basically need a custom serializer for each and every of our models (which we currently don't).

Maybe I'm missing something here - but what would the actual migration strategy be for a generic transform that's used in multiple models?

@knownasilya

knownasilya commented Jun 26, 2018 •

Copy link
Copy Markdown
Contributor

I would change the syntax instead, keeping string, number, boolean, and date (basically making them types) and making custom transform syntax as:

import transform from 'app/transforms/moment';
//...
// just a suggested API
dateUpdated: attr('date', {
  transform: transform({
    format: 'YYYY-MM-DD'
  })
}),

// OR

const options =  {
  format: 'YYYY-MM-DD'
};
// ..
dateUpdated: attr('date', {
  transform: {
    serialize(value) {
      // use options
    },
    deserialize(value) {
      // use options
    }
  }
}),

A transform be a function that takes options and returns a class/object with serialize and deserialize methods like now. A transform still basically assumes a base type, so it makes sense to combine attr with transform.

@buschtoens

Copy link
Copy Markdown
Contributor

@knownasilya What about non-standard types (i.e. custom classes) and arrays?

@runspired

Copy link
Copy Markdown
Contributor

@mydea

I don't really see how it would be easy to move this to serializers

Basically the issue here is that one bad pattern (per-type serializers) is endorsing another bad pattern as a compromise (transforms). That said, another way of looking at this is that you've already done exactly the thing you say you fear, just on the model instead of in the serializer where it belongs.

Our server can sometimes return null for array fields, so we have an array transform that ensures we end up with an empty array instead. We use this in multiple different models, and would have to add serializers for all of them.

You could do this once in the application serializer.

Then, we also have some common objects, which the server sends as inlined JSON objects, and we convert to actual class instances in transforms (and back to JSON when serializing). Again, this is used many times, and could theoretically be done in a serializer, but would be much more verbose.

It would likely be less verbose if done in the application serializer, especially if each class implements toJSON. That said, pushing custom classes as values on ember-data models is highly bug-prone and not something we have in the past officially supported. In addition to "dirty-tracking" not working for them, you would have to be careful to never mutate the reference. It is however an ability that RecordData unlocks.

Removing transforms and requiring to do all of this in serializers seems very un-DRY to me.

Transforms are anything but DRY, as they require you to do extensive additional work to be able to ensure mutations conform to a hidden and unofficial "type" that they lead you to believe exists, and must be repeated on every attr.

It would also mean that we'd basically need a custom serializer for each and every of our models (which we currently don't).

A single application serializer will do the trick. The serializer is always given the information of the model being serialized / deserialized.

what would the actual migration strategy be for a generic transform that's used in multiple models?

To use your array example.

const EMPTY_ARR_ATTRS = {
  'dashboard-user': ['settings', 'friends']
};

function normalizedEmptyArrAttrs(modelName, srcHash) {
    let attrsToNormalize = EMPTY_ARR_ATTRS[modelName];
    let attributes = {};

   if (attrsToNormalize !== undefined) {
     attrsToNormalize.forEach(attr => {
       attributes[attr] = srcHash[attr] === null ? [] : srcHash[attr];
     });
   }

  return attributes;
}

class Serializer {
  extractAttributes(modelClass, resourceHash) {
     let attributes = {};
     let { modelName } = modelClass;
     let srcAttributes = resourceHash.attributes;

     // ... do other things as necessary ...

    Object.assign(attributes, normalizeEmptyArrAttrs(modelName, srcAttributes));

     // ... do other things as necessary ...
  }
}

@runspired

Copy link
Copy Markdown
Contributor

@Alonski thanks for putting this together to get the conversation started!

We discussed this recently on the team meeting and it seems likely that instead of deprecating transforms we just leave them as a feature of the current model layer (yes, this implies a different model layer might exist, this was something enabled by the RecordData RFC and ember-m3 is one such alternative layer).

We will be splitting ember-data into multiple packages soon (RFCs coming), and while deprecating transforms would allow us to keep serializers and DS.Model as separate packages it wouldn't be too bad to keep them as a single unit for folks to replace with something that better works for them.

@runspired runspired added the T-ember-data RFCs that impact the ember-data library label Jun 26, 2018
@JCBarry

JCBarry commented Jun 27, 2018

Copy link
Copy Markdown

We use transforms a fair bit as well. Testing as it pertains to a transform is really nice, and does a nice job performing a "separation of duties" task. I always feel like the serializers end up with a LOT of code (this may just be because I work with APIs that don't conform to JSONAPI), but when that happens it becomes cumbersome to test/maintain. So, I'm not big advocate of letting serializers bear the brunt of this workload, especially considering there is already a reasonable pattern in place.

Reading the RFC, it seems the main issue is the confusion regarding types and I believe this confusion stems mostly from the design of the DS.attr() function. In most cases, the argument passed to that function (ex. string, number, date, etc) could all be reasonably perceived as a "type". The documentation for DS.attr() also references the first param as a "type" and by making a transform, it feels like you're making another "type" because of the way you end up using the transform:

export default DS.Model.extend({
  name: DS.attr('string'), // seems like a type
  age: DS.attr('number'), // seems like a type
  profile: DS.attr('markdown'), // custom transform, is it "markdown" a type?  
});

Perhaps as an alternative, transforms become options with a type of "object". So in practice, it could work along these lines:

export default DS.Model.extend({
  name: DS.attr('string'), // seems like a type
  age: DS.attr('number'), // seems like a type
  profile: DS.attr('object', { 
    transform: 'markdown'
  }), // Clearly and object, but uses a transform.
});

Again, most of my apprehension here is to avoid shoving more responsibilities onto the serializers. However, I can appreciate the delicate nature of transforms and their impact on performance if used incorrectly.

@luketheobscure

Copy link
Copy Markdown

Effective use of transforms has provided a great developer experience in our applications.

We use a custom transform when dealing with units on a model that provides access to things like conversion rates and translated names. All a developer has to do is declare fooUnit: attr('unit'). Forcing the developer to do that work in the serializer seems sub-optimal, especially since most models will inherit from the application serializer.

@christophersansone

christophersansone commented Jun 27, 2018 •

Copy link
Copy Markdown

Long time Ember user here. Transforms are one of my favorite parts of Ember Data and one of the main reasons I haven't moved to something else. Key benefits:

  • It automatically converts the data to the type of value that you define. That's awesome, right?
  • The attr() definitions help to annotate directly on the model which properties are server-based and what type of value they hold.
  • It minimizes the need to define custom serializers for every model type. I use JSON:API and have rarely had to declare a custom serializer.
  • It allows the developer to write a converter once across all serializers.

One of my most often used custom transforms is date-only, when the property is a date without a time. The server sends a date in the format of YYYY-MM-DD and expects the same format in return. Through the deserialization process, it becomes a Javascript Date object that I can safely pass it into moment or any date picker. And no matter how mangled the time may get along the way (which it often does in date pickers and across time zones), I know that the date will be sent to the server without the time.

I do believe there are strong reasons to keep transforms. If transforms did not exist, we could solve the same problem today through custom serializers, though the concept of an isolated, reusable attribute transformation seems like a good abstraction.

For me, it would help a lot to see what the proposed "new way" would be to replace a transform. Usually the RFCs have an "old way" vs. "proposed new way". Would someone be able to update the RFC to include that?

@runspired

Copy link
Copy Markdown
Contributor

Closing as it seems folks would prefer to leave transforms on the current model layer and as mentioned above we feel it would be less disruptive to enable folks to drop that model layer all at once vs in pieces.

I would encourage these folks to investigate the powers of serializers more thoroughly, as these sorts of transformations will nearly always be more clear when done there: this includes the case where one only uses one or a small handful of serializers (such as one per API).

@runspired runspired closed this Jun 27, 2018
@knownasilya

Copy link
Copy Markdown
Contributor

@runspired maybe a blog post or stream would help guide people in how to do this properly, in a testable way?

@sandstrom

sandstrom commented Jun 28, 2018 •

Copy link
Copy Markdown
Contributor

@Alonski Thanks for bringing this up for discussion! 🏅

I have three main comments:

  1. I agree with all of what @JCBarry said above. Basically that the blur between attribute types and transforms could be improved, but I don't think we should remove transforms.

  2. I also think that transforms as concept (if separate from the attribute type), could be moved to the serializer layer, in other words, the transforms that should be applied to different model attributes should be specified in the serializer, not the model.

  3. We should keep transforms around. The idea itself — shared logic for transforming scalar values and data structures — is very useful.

@gustaff-weldon

Copy link
Copy Markdown

We breathe transforms.
We have special ones that convert slugs like male, en-us to objects with more data, or date strings to Moment objects for easier manipulation.
Thanks to transforms being very simple serialize/deserialize constructs they are highly reusable. We reuse them across many models eg. attr('gender'), no serialiser logic needed.
This RFC does not seem to propose any DRY alternative - eg. maybe moving transforms to serializers' attrs definition instead?

@mehulkar

mehulkar commented Jul 3, 2018 •

Copy link
Copy Markdown

Transforms are not types.

Maybe a silly question, but can someone explain why this is? If a transform can guarantee that a property will be a string or number or someCustomThing, why is it wrong to think of it as a type?

edit: for what it's worth, I like transforms for documentation mostly. Looking at a model and knowing what a property is expected to be is a nice alternative to having a schema file. An equivalent API could probably exist in serializers though, so I'm not particularly attached to transforms in their current form.

@runspired

Copy link
Copy Markdown
Contributor

@mehulkar transforms have zero guarantees. They are only used by the serializer, not the model (so calls to set simply clobber them), their state isn't tracked, and almost any serializer customization will result in them not being used at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-ember-data RFCs that impact the ember-data library

Projects

None yet

Development

Successfully merging this pull request may close these issues.