Search code examples
ember.jsember-dataember-cli

ember-cli mocks doesn't return single record


I'm building a simple ember-cli app. And I tried to implement new mocks feature.

server/mocks/users.js

module.exports = function (app) {
  var express = require('express');
  var usersRouter = express.Router();
  usersRouter.get('/', function (req, res) {
    res.send({"users": [
      {
        "id": 1,
        "login": 'berdof'
      },
      {
        "id": 2,
        "login": 'berdof2'
      }
    ]});
  });
  app.use('/api/users', usersRouter);
};

Next when I'm trying to fetch the data, for instance in browser, I just open

http://0.0.0.0:4200/api/user/

and get the correct data. But when I want to fetch a single record it just throws me an error

Cannot GET /api/users/1

Do you know why's that? I've been fighting with this bug for about 2 hours. Thanks you for any help! Have a good day!

Update

Here's the modified answer according to @kaungst post:

module.exports = function (app) {
  var express = require('express');
  var router = express.Router();
  var dataToSend = [
    {
      id: 1,
      login: 'berdof',
    },
    {
      id: 1,
      login: 'berdof2'
    }
  ];

  router.get('/', function (req, res) {
    res.send({"users": dataToSend});
  });
  router.get('/:id', function (req, res) {
    var id = req.params.id;
    res.send({"user": dataToSend[id]});
  });
  app.use('/api/users', router);
};

Solution

  • you have to create an additional mock to handle that case

    for this specific example run

    ember g http-mock user
    

    which should generate the following in <\app-name>/server/mocks/user.js

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

    alter it to look like this

    module.exports = function (app) {
        var express = require('express');
        var userRouter = express.Router();
        userRouter.get('/', function (req, res) {
            // this part is hacky but works
            // main thing is to decide what you want to send
            // happy to update if someone knows a better solution
            var url = req.baseUrl.split('/');
            var id = parseInt(url[url.length-1]);
            var users = [{
                "id": 1,
                "login": 'berdof'
                },
                {
                "id": 2,
                "login": 'berdof2'
            }];
    
            res.send({"user": users[id]});
        });
        app.use('/api/user/:id', userRouter);
    };