From e8fe1ad89a7188a53631b632003f7814deddcc1c Mon Sep 17 00:00:00 2001 From: Typicode Date: Mon, 25 May 2015 14:48:22 +0200 Subject: [PATCH] Add embed, thanks to @delfi --- src/router.js | 14 +++++++++++++- test/index.js | 27 ++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/router.js b/src/router.js index 293497a..c6129be 100644 --- a/src/router.js +++ b/src/router.js @@ -101,7 +101,7 @@ module.exports = function (source) { filters[key] = utils.toNative(req.query[key]) } } - + // Filter if (_(filters).isEmpty()) { array = db(req.params.resource).value() @@ -144,10 +144,22 @@ module.exports = function (source) { // GET /:resource/:id function show (req, res, next) { + var _embed = req.query._embed var resource = db(req.params.resource) .get(utils.toNative(req.params.id)) if (resource) { + // Always use an array + _embed = _.isArray(_embed) ? _embed : [_embed] + + // Embed other resources based on resource id + _embed.forEach(function () { + var query = {} + query[req.params.resource + 'Id'] = req.params.id + resource[_embed] = db(_embed).where(query) + }) + + // Return resource res.jsonp(resource) } else { res.status(404).jsonp({}) diff --git a/test/index.js b/test/index.js index 3ebd4c9..bf44313 100644 --- a/test/index.js +++ b/test/index.js @@ -111,7 +111,7 @@ describe('Server', function () { }) }) - describe('GET /:resource?sort=', function () { + describe('GET /:resource?_sort=', function () { it('should respond with json and sort on a field', function (done) { request(server) .get('/tags?_sort=body') @@ -200,6 +200,31 @@ describe('Server', function () { }) }) + describe('GET /:resource/:id?_embed=', function () { + it('should respond with corresponding resource and embedded other resource', function (done) { + var posts = db.posts[0] + posts.comments = [db.comments[0], db.comments[1]] + request(server) + .get('/posts/1?_embed=comments') + .expect('Content-Type', /json/) + .expect(posts) + .expect(200, done) + }) + }) + + describe('GET /:resource/:id?_embed=&_embed=', function () { + it('should respond with corresponding resource and embedded other resources', function (done) { + var posts = db.posts[0] + posts.comments = [db.comments[0], db.comments[1]] + posts.refs = [db.refs[0]] + request(server) + .get('/posts/1?_embed=comments&_embed=refs') + .expect('Content-Type', /json/) + .expect(posts) + .expect(200, done) + }) + }) + describe('POST /:resource', function () { it('should respond with json, create a resource and increment id', function (done) {