mirror of
https://github.com/typicode/json-server.git
synced 2025-07-27 20:23:34 +08:00
Add embed, thanks to @delfi
This commit is contained in:
@ -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({})
|
||||
|
@ -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) {
|
||||
|
Reference in New Issue
Block a user