Skip to content

Commit dd2be29

Browse files
authored
Merge pull request #61 from jkyberneees/adding-url-rewrite
Adding url rewrite hook
2 parents 5d1aa7f + f641208 commit dd2be29

File tree

4 files changed

+26
-2
lines changed

4 files changed

+26
-2
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ module.exports.handler = serverless(service)
141141
},
142142
// Optional "prefix rewrite" before request is forwarded. Default value: ''
143143
prefixRewrite: '',
144+
// Optional "url rewrite" hook. If defined, the prefixRewrite setting is ignored.
145+
urlRewrite: (req) => req.url,
144146
// Remote HTTP server URL to forward the request.
145147
// If proxyType = 'lambda', the value is the name of the Lambda function, version, or alias.
146148
target: 'http://localhost:3000',

demos/url-rewrite.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict'
2+
3+
const gateway = require('../index')
4+
const PORT = process.env.PORT || 8080
5+
6+
gateway({
7+
routes: [{
8+
pathRegex: '',
9+
prefix: '/customers/:customerId',
10+
target: 'http://localhost:3000',
11+
urlRewrite: ({ params: { customerId } }) => `/users/${customerId}`
12+
}]
13+
}).start(PORT).then(server => {
14+
console.log(`API Gateway listening on ${PORT} port!`)
15+
})
16+
17+
const service = require('restana')({})
18+
service
19+
.get('/users/:id', (req, res) => res.send('Hello ' + req.params.id))
20+
.start(3000).then(() => console.log('Service listening on 3000 port!'))

index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,9 @@ const gateway = (opts) => {
9191

9292
const handler = (route, proxy, proxyHandler) => async (req, res, next) => {
9393
try {
94-
req.url = req.url.replace(route.prefix, route.prefixRewrite)
94+
req.url = route.urlRewrite
95+
? route.urlRewrite(req)
96+
: req.url.replace(route.prefix, route.prefixRewrite)
9597
const shouldAbortProxy = await route.hooks.onRequest(req, res)
9698
if (!shouldAbortProxy) {
9799
const proxyOpts = Object.assign({

test/config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ module.exports = async () => {
6969
{
7070
pathRegex: '',
7171
prefix: '/endpoint-proxy-methods',
72-
prefixRewrite: '/endpoint-proxy-methods',
72+
urlRewrite: (req) => '/endpoint-proxy-methods',
7373
target: 'http://localhost:3000',
7474
methods: ['GET', 'POST']
7575
},

0 commit comments

Comments
 (0)