Search code examples
ember.jsember-dataember-cli-mirage

How to create a object in ember-cli-mirage?


I have a foo model that hasMany bar and bar belongsTo baz. How can I include the creation of baz when a foo is created together with it's bar? Whenver a foo is created a 10 bar must create and a baz is created for each bar

On my /factories/foo.js I have a

  afterCreate(foo, server) {
    server.createList('bar', 10, { foo });
  }

Solution

  • One option would be to have the bar factory create its own baz:

    // factories/bar.js
    export default Factory.extend({
      afterCreate(bar, server) {
        bar.update({
          baz: server.create('baz')
        })
      }
    })
    

    This way, every time server.create('bar') is called (no matter where), each bar would get updated with its own baz.

    You could even use the association helper to do this for you – it basically takes care of this special case of creating a belongsTo relationship whenever the base model is created:

    import { Factory, association } from 'ember-cli-mirage';
    
    // factories/bar.js
    export default Factory.extend({
      baz: association()
    })
    

    You could also do it directly from the foo factory:

    // factories/foo.js
    afterCreate(foo, server) {
      server.createList('bar', 10, { foo }).forEach(bar => {
        bar.update({
          baz: server.create('baz')
        })
      });
    }
    

    Just note that base factories should be the minimal valid descriptions of your models + their relationships – if you put these auto-creating relationships in each base factory and then someone wants to write a test for a situation where these relationships don't exist, it'll be difficult for them. The traits feature is designed specifically to alleviate this sort of thing:

    // factories/bar.js
    Factory.extend({
      withBaz: trait({
        baz: association()
      })
    })
    
    // factories/foo.js
    Factory.extend({
      afterCreate(foo, server) {
        server.createList('bar', 10, 'withBaz', { foo });
      }
    })
    

    Also be sure to give the factory best practices guide a read! :)