Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the new ember-cli http-mock for API calls

I have a simple (so far) ember-cli project, and right now just have one model with FIXTURE data. I would like to mock up API stuff, either with actual JSON files, or with http-mock, which is the ember-cli version 41 name of what used to be api-stub.

I'm pretty new to all this, so I really didn't know what to make of the info I found where people were able to get api-stub working, and it doesn't look like any docs on the ember-cli have been updated with http-mock info yet.

I did do ember generate http-mock project but I'm not sure really what to do from here.

Here's my current app/router.js:

Router.map(function() {
  this.resource('projects', { path: '/' });
  this.resource('project', {path: '/project/:project_id'}, function(){
    this.resource('milestones');
    this.resource('team');
    this.resource('budget');
  });
});

So I have a template for all my projects, and want to drill down to one, which need to be able to relate to the nested routes. My ideal would be something like the GitHub API where you can drill down from a user to a repo, to issues on that repo, etc.

Again, I'm still learning my way around ember and ember-cli, so explanations of "why" as well as "how" are hugely appreciated.

like image 746
redOctober13 Avatar asked Aug 28 '14 13:08

redOctober13


1 Answers

I'm fairly new to ember/ember-cli as well but I got a simple http-mock prototype working. After generating your http-mock project:

>ember g http-mock project

The generator should have created a 'server' folder within your project with your project.js mock in the 'mocks' subdirectory. If you open up that file (server/mocks/project.js) you should see something like this:

module.exports = function(app) {
  var express = require('express');
  var projectRouter = express.Router();
  projectRouter.get('/', function(req, res) {
    res.send({project:[]});
  });
  app.use('/api/project', projectRouter);
};

You'll want to update the res.send(...) with the json your api should respond with. eg:

res.send({project:{id: 1, number: 123, name: 'Fooshnickins'}});

You can prove to yourself this works by running your server:

>ember server

And curl'ing your api (note the content type):

>curl -H "ContentType:application/json" http://localhost:4200/api/project

Should respond with:

{project:{id: 1, number: 123, name: 'Fooshnickins'}}
like image 129
GOULETGOULET Avatar answered Nov 09 '22 10:11

GOULETGOULET