diff --git a/src/server/rewriter.js b/src/server/rewriter.js index 718220f37..a48e91069 100644 --- a/src/server/rewriter.js +++ b/src/server/rewriter.js @@ -1,7 +1,9 @@ const express = require('express') const url = require('url') const _ = require('lodash') - +function updateQueryString(target,sourceUrl) { + return !!~sourceUrl.indexOf('?') ? _.assign(target, url.parse(sourceUrl, true).query) : {}; +} module.exports = (routes) => { const router = express.Router() @@ -14,16 +16,14 @@ module.exports = (routes) => { target = target.replace(':' + param, req.params[param]) } req.url = target - if (target.indexOf('?')) { - // create query from target - _.assign(req.query, url.parse(target, true).query) - } + req.query = updateQueryString(req.query,req.url) next() }) } else { router.all(route + '*', (req, res, next) => { // Rewrite url by replacing prefix req.url = req.url.replace(route, routes[route]) + req.query = updateQueryString(req.query,req.url) next() }) } diff --git a/test/server/plural.js b/test/server/plural.js index 9a0918b04..25103b67d 100644 --- a/test/server/plural.js +++ b/test/server/plural.js @@ -78,7 +78,9 @@ describe('Server', () => { server.use(jsonServer.rewriter({ '/api/': '/', '/blog/posts/:id/show': '/posts/:id', - '/comments/special/:userId-:body': '/comments/?userId=:userId&body=:body' + '/comments/special/:userId-:body': '/comments/?userId=:userId&body=:body', + '/firstpostwithcomments': '/posts/1?_embed=comments' + })) server.use(router) }) @@ -686,6 +688,15 @@ describe('Server', () => { .end(done) }) + it('should rewrite using query without params', function (done) { + const expectedPost = _.cloneDeep(db.posts[0]) + expectedPost.comments = [ db.comments[0], db.comments[1] ] + request(server) + .get('/firstpostwithcomments') + .expect(expectedPost) + .end(done) + }) + it('should rewrite using params and query', function (done) { request(server) .get('/comments/special/1-quux')