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.
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:
- It imported the faker library
var faker = require('faker');
- 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;
}
- 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)
});
});
It also goes without saying that it will also generate the necessary tests.