Search code examples
serializationember.jsember-data

Ember.js - Accessing nested data via serializer


What is the best approach for accessing a single nested record in Ember?

The JSON response which we are trying to manipulate looks gets returned as the following: (the attribute being targeted is the tradeIdentifier property)

trade:
    tradeIdentifier:"83f3f561-62af-11e7-958b-028c04d7e8f9"
    tradeName:"Plumber"
userEmail:"test@gmail.com"

The project-user model looks partially like:

  email: attr('string'),
  trade:attr(),
  tradeId: attr(),

The project-user serializer looks partially like:

export default UndefinedOmitted.extend(EmbeddedRecordsMixin, {
  primaryKey: 'userRoleId',
  attrs: {
    'email': { key: 'userEmail' },
    'trade': { key: 'trade' },
    'tradeId': { key: 'tradeIdentifier' },
  },
});

The trade attr here is a placeholder to make sure that the data was accessible. I would like to be able to access the tradeIdentifier without having to do the following in the component:

const trade = get(formRole, 'trade');
if (trade) {
  set(formProps, 'tradeId', trade.tradeIdentifier);
}

Have tested creating a trade-id transform (referenced via tradeId: attr('trade-id')), however to no avail.

export default Transform.extend({
  deserialize(val) {

    const trade = val;
    const tradeId = val.tradeIdentifier;

    return tradeId;
  },
  serialize(val) {
    return val;
  },
});

Can anyone suggest where I'm going wrong?


Solution

  • A transform seems a bit overkill for what I'm trying to achieve here, however it does the job. Managed to get it working by modifying the following:

    In serializers/project-user.js:

    'tradeId': { key: 'trade' },

    Note that this references the property in the payload to transform, not the property being targeted (which was my mistake).

    In models/project-user.js:

    tradeId: attr('trade-id'),

    Attribute references the transform.

    In transform/trade-id.js:

    export default Transform.extend({
      deserialize(val) {
    
        let tradeId = val
        if (tradeId) {
          tradeId = val.tradeIdentifier;
        }
    
        return tradeId;
      },
      serialize(val) {
        return val;
      },
    });
    

    If there's a simpler solution outside of transforms, I would still be open to suggestions.