Recommand · June 7, 2021 0

Run multiple serializers for embedded models in miragejs

I’m working with reactjs and am using miragejs to mock the backend. I have two models, User and Event. Each user hasMany events and each event is ownedBy a user. I’m using a factory to mock events which only gives the event a start time.
Since the start time is randomized, I can’t generate an end time in the factory so I do that when the event is serialized. As you can see, in the serializer portion I check if the end property exists. If it does not, then I add an end property to it. However, when I run schema.users.all() only the users serializer gets called and not the embedded event objects. Is it possible to configure mirage so that both serializers would run? I have looked over the miragejs documentation for serializers and it says the serializer function

Returns a plain JavaScript object or array, which Mirage uses as the response data to your app’s XHR request.

Does that mean that only one serializer can ever run and that one being the top level, or parent model. In this case being user?

Event Factory

export const factories = {
  event: Factory.extend({
    title: 'Title',
    start() {
      const randomStartOffset = (Math.random()*9).toFixed(0);
      const startOfDay = moment().startOf('day').add(9, 'hr').add(randomStartOffset, 'hours')
      const startDate = startOfDay.clone().subtract(1, 'week').toISOString();
      const endDate = startOfDay.clone().add(1, 'month');
      return moment(, endDate)).startOf('hour')


export const serializers = {
  user: ApplicationSerializer.extend({
    include(request) {
      const include = [];
      if (request.queryParams.includeEvents) include.push('events');
      return include;
    serialize() {
      let json = Serializer.prototype.serialize.apply(this, arguments);
      return json
  event: ApplicationSerializer.extend({
    serialize(object, request) {
      let json = Serializer.prototype.serialize.apply(this, arguments);
      if (!('end' in json))
      json.end = moment(json.start).add(1, 'hour')
      return json;