Skip to content

Instantly share code, notes, and snippets.

@cullymason
Last active August 29, 2015 14:17
Show Gist options
  • Save cullymason/84b8817720cdf92ae73d to your computer and use it in GitHub Desktop.
Save cullymason/84b8817720cdf92ae73d to your computer and use it in GitHub Desktop.

Mock-Fake

Purpose

Add new command to ember-cli to speed up prototyping out a new idea like this:

ember generate mock-fake post --fields="title:string, body:string, comment:hasMany, author:belongsTo" 

With that one command you will have everything you need to fake a backend for your ember app.

Explanation

The command would generate a few files

app/models/post.js

import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr('string'),
    body: DS.attr('string'),
    comments: DS.hasMany('comment'),
    author: DS.belongsTo('author')
});

So it generates a model file and populates the attributes for you. Relationships are listed in the singular/plural form based on the relationship type.

server/mocks/posts.js

module.exports = function(app) {
  var express = require('express');
  var faker = require('faker');
  var postsRouter = express.Router();
  var POSTS = function(iterations) {
    p = [];
    for (var i = 0; i < iterations; i++) {
      p[i] = {
        id: i+1,
        title: faker.lorem.sentence(),
        body: faker.lorem.sentence),
        comments: [1],
        author: 1
      }
    };
    return p;
  }
  postsRouter.get('/', function(req, res) {
    res.send({
      'posts': POSTS(9)
    });
  });
 //... 

A few things to notice:

  1. It imported the faker library
var faker = require('faker');
  1. then creates a POSTS variable that generates the fake date based on the --fields that was passed in the command. Relationships are listed in the singular/plural form based on the relationship type.
var POSTS = function(iterations) {
    p = [];
    for (var i = 0; i < iterations; i++) {
      p[i] = {
        id: i+1,
        title: faker.lorem.sentence(),
        body: faker.lorem.sentence),
        comments: [1],
        author: 1
      }
    };
    return p;
  }
  1. and finally, we reference that variable so that when api/posts is called, it will return the fake data
 postsRouter.get('/', function(req, res) {
  res.send({
    'posts': POSTS(9)
  });
});

Thoughts?

@cullymason
Copy link
Author

It also goes without saying that it will also generate the necessary tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment