How to omit attributes in ember.js?

Member

by domenico , in category: Javascript , 5 months ago

How to omit attributes in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 2 months ago

@domenico 

In Ember.js, there is no built-in way to omit specific attributes from a model when it is being serialized. However, you can achieve this by defining a custom serializer for your model and implementing the normalizeResponse method to omit the attributes you don't want to include.


Here is an example of how you can omit attributes using a custom serializer:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// app/serializers/custom-serializer.js

import JSONSerializer from '@ember-data/serializer/json';

export default JSONSerializer.extend({
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    if (requestType === 'findRecord' || requestType === 'queryRecord') {
      // Omit the 'secretAttribute' from the payload
      delete payload.secretAttribute;
    }

    return this._super(...arguments);
  }
});


In this example, we are creating a custom serializer that extends JSONSerializer and overrides the normalizeResponse method to remove the secretAttribute from the payload before it gets normalized.


You can then specify this custom serializer for your model by setting the serializer property in your model definition like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// app/models/your-model.js

import Model from '@ember-data/model';
import attr from '@ember-data/model/attr';
import { inject as service } from '@ember/service';

export default Model.extend({
  customSerializer: service(),

  serializer: 'custom-serializer',

  // Define the model attributes here
  name: attr('string'),
  age: attr('number'),
  secretAttribute: attr('string')
});


By setting the serializer property to custom-serializer, Ember.js will use your custom serializer to serialize and deserialize your model, and the secretAttribute will be omitted from the response when you request the model.