Skip to content

Instantly share code, notes, and snippets.

@eliotsykes
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliotsykes/6702e4abac3c1f39a14f to your computer and use it in GitHub Desktop.
Save eliotsykes/6702e4abac3c1f39a14f to your computer and use it in GitHub Desktop.
Ember.js Server Mock with id sequence and req.body JSON
// Generated originally with `ember g http-mock todos`,
// then customized so JSON body parsing is available.
module.exports = function(app) {
var express = require('express');
var todosRouter = express.Router();
// Install body-parser: `npm install --save-dev body-parser`
// Body parser needed so req.body is
// available to router endpoints as JS object.
var bodyParser = require('body-parser');
// Use the JSON parser middleware
todosRouter.use(bodyParser.json());
// Incrementing ids
var idSequence = {
next: (function() {
var nextId = 1;
return function() {
var id = nextId;
nextId = nextId + 1;
return id;
};
})()
};
todosRouter.get('/', function(req, res) {
res.send({
'todos': [
{
id: idSequence.next(),
title: 'Learn Ember.js',
isCompleted: true
},
{
id: idSequence.next(),
title: '...',
isCompleted: false
},
{
id: idSequence.next(),
title: 'Profit!',
isCompleted: false
}
]
});
});
todosRouter.post('/', function(req, res) {
var todo = req.body.todo;
res.status(201).send({
'todos': {
id: idSequence.next(),
title: todo.title,
isCompleted: todo.isCompleted
}
});
});
todosRouter.get('/:id', function(req, res) {
res.send({
'todos': {
id: req.params.id
}
});
});
todosRouter.put('/:id', function(req, res) {
res.send({
'todos': {
id: req.params.id
}
});
});
todosRouter.delete('/:id', function(req, res) {
res.status(204).end();
});
app.use('/api/todos', todosRouter);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment