Skip to content

Instantly share code, notes, and snippets.

@gerhardberger
Last active August 29, 2015 14:10
Show Gist options
  • Save gerhardberger/c6987ebe8ac68150defb to your computer and use it in GitHub Desktop.
Save gerhardberger/c6987ebe8ac68150defb to your computer and use it in GitHub Desktop.
// mw.js
var mw = function (options) {
return function *(next) {
this.db = options.db;
yield next;
}
}
// server.js
var mw = require('mw');
var db = require('memdb');
module.exports = function (app) {
app.use(bodyParser());
app.use(mw({
db: db;
}))
app.use(_.get('/cats/:ids', function *(ids) {
try {
var data = yield ids.split(',').map(function (id) {
return this.db.get(id);
});
} catch (e) {
console.log('ERROR');
}
this.type = 'application/vnd.api+json';
this.status = 200;
this.body = JSON.stringify(data.length > 1 ? { body: data } : data[0]);
}));
return app;
}
// test.js
test('fetching a cat', function (t) {
var app = koa();
app.use(mw({
db: {
get: function (id) {
var o = { bar: { name: 'mici' id: 'bar' } };
return [ o[id] ];
}
}
}));
catDB(app);
request(app.listen())
.get('/cats/bar')
.expect('Content-Type', 'application/vnd.api+json')
.end(function (err, res) {
if (err) t.end(err);
t.equals(200, res.status);
t.same(JSON.parse(res.text), { name: 'mici', id: 'bar' });
t.end();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment