Call Us: +1-888-227-1645
Seeding relations in Ember Mirage

Seeding Relations in Ember Mirage with Factories

javascript

Eric Meyer

2 min read

When we are working on an EmberJs project, for all but the most trivial applications, we like to mock API calls so we can develop the UI of our application independently of the back end. Enter in Ember-cli-Mirage. a really essential library maintained by Sam Selikoff.

We’re not going to deep dive into all of the features that Ember-Mirage offers, but rather point out a feature thats really handy when creating object relations in your mock api. When you use a factory to populate your database, you can create the data relation right in the factory.

Take for example the idea of posts and comments. Lets imagine in your system that one post has many comments. You’ve created a model for your Post object. Ember-cli-mirage now supports models with relations, btw:

(Note that I am leaving out any attributes in these examples, only the relations. Of course your post is going to have authors, etc)

import { Model , hasMany } from 'ember-cli-mirage';

export default Model.extend({
  comments:hasMany('comment'),
});

And you also have created the comment object:

import { Model, belongsTo } from 'ember-cli-mirage';

export default Model.extend({
  post:belongsTo('post'),
});

Now that we have established the relationships of our objects using the models, lets look at the factories that will create them, specifically the post factory. What we want to do, is any time the post factory runs, we want to mock up a bunch of comments to go along with it. We can do this with the afterCreate() hook in the factory itself:

import { Factory, faker } from 'ember-cli-mirage';

export default Factory.extend({

  afterCreate(comment, server) {
     server.createList('comment', 10 ,{post});
  }

});

In the afterCreate hook above, we are creating 10 comments, and attaching the postId to the comment. We can then run Server.createList(‘post’,10); in our /scenarios/default.js file. For each Post, the factory will then generate the complimentary comments.

From the blog

Latest Articles

Let's build something amazing together

Give us a ring and let us know how we can help you reach your goals. Or if you'd like, start a chat. We're usually available 9-5 EST. We try to respond to every inquiry within one business day.

Phone number
+1-888-227-1645

Technologies and services we work with:

Laravel Laravel
WordPress WordPress
React ReactJS
EmberJS EmberJS
woocommerce WooCommerce
next.js NextJS
gatsby Gatsby
Shopify Shopify
VueJs VueJS
contentful Contentful
next.js JAMStack
gatsby Laravel Jigsaw
WPEngine WP Engine
Laravel Livewire Laravel Livewire
Netlify Netlify