Skip to content

Instantly share code, notes, and snippets.

@A
Created May 21, 2015 16:40
Show Gist options
  • Save A/2405f6d4e4bb81fb6684 to your computer and use it in GitHub Desktop.
Save A/2405f6d4e4bb81fb6684 to your computer and use it in GitHub Desktop.
REST API mocks for superagent and superagent-mocker
'use strict';
/**
* Dependencies
*/
var mock = require('superagent-mocker');
var _ = require('lodash');
/**
* Default fixtures
*/
var fixtures = [
{
id: 1,
title: 'First article',
body: 'Lorem ipsum…',
creatorId: 1
},
{
id: 1,
title: 'Second article',
body: 'Sed non satiata…',
creatorId: 3
}
];
/**
* Mocks for the API
*/
mock.get('/articles/:id', function(req) {
var id = req.params.id|0;
var res = _.findWhere(fixtures, { id: id }) || {};
return res;
});
mock.get('/articles/', function(req) {
return fixtures;
});
mock.post('/articles/', function(req) {
var id = req.params.id|0;
var item = req.body;
item.id = nextID();
fixtures.push(item);
return item;
});
mock.put('/articles/:id', function(req) {
var id = req.params.id|0;
var item = _.findWhere(fixtures, { id: id });
return _.extend(item, req.body);
});
mock.del('/articles/:id', function(req) {
var id = req.params.id|0;
var removed = _.findWhere(fixtures, { id: id });
var index = fixtures.indexOf(removed);
fixtures.splice(index, 1);
return removed;
});
/**
* get new id
* @return {int} id
*/
function nextID() {
var ids = fixtures.map(function(item) { return item.id; });
return Math.max.apply(Math, ids) + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment