Search code examples
ember.jsember-cli-mirage

EmberJS Mirage Dependent attributes do not update on patch


I have declared a properties in a Mirage factory as below and using Dependent attributes as found in the docs.

price() {
  return faker.finance.amount(100000, null, 0);
},

priceDisplay() {
  return '$' + this.price;
}

When I do a patch to update price I expect priceDisplay to update as well like a computed property however this is not the case.

Does anyone know if this is possible or is this a Mirage limitation?


Solution

  • Mirage factory are meant to generate testing data:

    Factories are classes that help you organize your data-creation logic, making it easier to define different server states during development or within tests.

    The factory is only run once by server.create('foo') or server.createList('foo', 10) to create initial data for the records. This helps you to avoid code duplication in tests and scenarios. But it's not a model representing that record.

    Actually Mirage does not support something like computed properties out of the box. But you could achieve it by customizing the serializer used. Overriding the serialize method should do the trick:

    // serializers/product.js
    
    import { JSONAPISerializer } from 'ember-cli-mirage';
    
    export default JSONAPISerializer.extend({
      // This is how to call super, as Mirage borrows [Backbone's implementation of extend](http://backbonejs.org/#Model-extend)
      let json = Serializer.prototype.serialize.apply(this, arguments);
    
      json.priceDisplay = '$' + json.price;
    
      return json;
    });
    

    But from your example given I would question if returning a formatted string from the API is the right approach. Formatting data should be a concern of the client in my opinion. Otherwise you will quickly run into limitations if you need to support localization or require different formats in your client.