Update rewriter (#580)

This commit is contained in:
typicode
2017-07-05 13:17:10 +02:00
committed by GitHub
parent d5ac11f5ca
commit 21d2fff3a9
7 changed files with 43 additions and 44 deletions

View File

@ -1,8 +1,15 @@
# Change Log # Change Log
## 0.11.0 - 2017-07-05
Switch to [express-urlrewrite](https://github.com/kapouer/express-urlrewrite) to support rewriting query parameters (e.g. `/articles?id=1 # → /posts/1`)
If you're rewriting default routes, you'll need to update your `routes.json` file
(see [add custom routes](https://github.com/typicode/json-server#add-custom-routes) for updated doc).
## 0.10.3 - 2017-06-28 ## 0.10.3 - 2017-06-28
* Fix line-break error in CLI * Fix `line-break` error in CLI
## 0.10.2 - 2017-06-28 ## 0.10.2 - 2017-06-28

View File

@ -314,9 +314,10 @@ Create a `routes.json` file. Pay attention to start every route with `/`.
```json ```json
{ {
"/api/": "/", "/api/*": "/$1",
"/blog/:resource/:id/show": "/:resource/:id", "/:resource/:id/show": "/:resource/:id",
"/blog/:category": "/posts?category=:category" "/posts/:category": "/posts?category=:category",
"/articles\\?id=:id": "/posts/:id"
} }
``` ```
@ -331,8 +332,9 @@ Now you can access resources using additional routes.
```sh ```sh
/api/posts # → /posts /api/posts # → /posts
/api/posts/1 # → /posts/1 /api/posts/1 # → /posts/1
/blog/posts/1/show # → /posts/1 /posts/1/show # → /posts/1
/blog/javascript # → /posts?category=javascript /posts/javascript # → /posts?category=javascript
/articles?id=1 # → /posts/1
``` ```
### Add middlewares ### Add middlewares

17
package-lock.json generated
View File

@ -1236,6 +1236,23 @@
"resolved": "https://registry.npmjs.org/express/-/express-4.15.3.tgz", "resolved": "https://registry.npmjs.org/express/-/express-4.15.3.tgz",
"integrity": "sha1-urZdDwOqgMNYQIly/HAPkWlEtmI=" "integrity": "sha1-urZdDwOqgMNYQIly/HAPkWlEtmI="
}, },
"express-urlrewrite": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/express-urlrewrite/-/express-urlrewrite-1.2.0.tgz",
"integrity": "sha1-jmZ7d2H/HH/9sO+gXWQDU4fII+s=",
"dependencies": {
"isarray": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8="
},
"path-to-regexp": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.7.0.tgz",
"integrity": "sha1-Wf3g9DW62suhA6hOnTvGTpa5k30="
}
}
},
"extend": { "extend": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz",

View File

@ -15,6 +15,7 @@
"cors": "^2.3.0", "cors": "^2.3.0",
"errorhandler": "^1.2.0", "errorhandler": "^1.2.0",
"express": "^4.9.5", "express": "^4.9.5",
"express-urlrewrite": "^1.2.0",
"json-parse-helpfulerror": "^1.0.3", "json-parse-helpfulerror": "^1.0.3",
"lodash": "^4.11.2", "lodash": "^4.11.2",
"lodash-id": "^0.13.0", "lodash-id": "^0.13.0",

View File

@ -1,11 +1,6 @@
const express = require('express') const express = require('express')
const url = require('url') const rewrite = require('express-urlrewrite')
const _ = require('lodash')
function updateQueryString(target, sourceUrl) {
return ~sourceUrl.indexOf('?')
? _.assign(target, url.parse(sourceUrl, true).query)
: {}
}
module.exports = routes => { module.exports = routes => {
const router = express.Router() const router = express.Router()
@ -13,26 +8,8 @@ module.exports = routes => {
res.json(routes) res.json(routes)
}) })
Object.keys(routes).forEach(route => { Object.keys(routes).forEach(key => {
if (route.indexOf(':') !== -1) { router.use(rewrite(key, routes[key]))
router.all(route, (req, res, next) => {
// Rewrite target url using params
let target = routes[route]
for (let param in req.params) {
target = target.replace(`:${param}`, req.params[param])
}
req.url = target
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()
})
}
}) })
return router return router

View File

@ -42,7 +42,7 @@ describe('cli', () => {
) )
routesFile = tempWrite.sync( routesFile = tempWrite.sync(
JSON.stringify({ '/blog/': '/' }), JSON.stringify({ '/blog/*': '/$1' }),
'routes.json' 'routes.json'
) )
@ -260,7 +260,7 @@ describe('cli', () => {
}) })
it('should watch routes file', done => { it('should watch routes file', done => {
fs.writeFileSync(routesFile, JSON.stringify({ '/api/': '/' })) fs.writeFileSync(routesFile, JSON.stringify({ '/api/*': '/$1' }))
setTimeout(() => { setTimeout(() => {
request.get('/api/posts').expect(200, done) request.get('/api/posts').expect(200, done)
}, 1000) }, 1000)

View File

@ -8,11 +8,11 @@ describe('Server', () => {
let router let router
let db let db
const rewriterRules = { const rewriterRules = {
'/api/': '/', '/api/*': '/$1',
'/blog/posts/:id/show': '/posts/:id', '/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', '/firstpostwithcomments': '/posts/1?_embed=comments',
'/articles?_id=:id': '/posts/:id' '/articles\\?_id=:id': '/posts/:id'
} }
beforeEach(() => { beforeEach(() => {
@ -660,13 +660,8 @@ describe('Server', () => {
it('should rewrite using params and query', () => it('should rewrite using params and query', () =>
request(server).get('/comments/special/1-quux').expect([db.comments[4]])) request(server).get('/comments/special/1-quux').expect([db.comments[4]]))
// TODO it('should rewrite query params', () =>
// it('should rewrite query params', () => ( request(server).get('/articles?_id=1').expect(db.posts[0]))
// request(server)
// .get('/articles?_id=1')
// .expect(db.posts[0])
// .end(done)
// })
it('should expose routes', () => it('should expose routes', () =>
request(server).get('/__rules').expect(rewriterRules)) request(server).get('/__rules').expect(rewriterRules))