Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ module.exports.handler = serverless(service)
},
// Optional "prefix rewrite" before request is forwarded. Default value: ''
prefixRewrite: '',
// Optional "url rewrite" hook. If defined, the prefixRewrite setting is ignored.
urlRewrite: (req) => req.url,
// Remote HTTP server URL to forward the request.
// If proxyType = 'lambda', the value is the name of the Lambda function, version, or alias.
target: 'http://localhost:3000',
Expand Down
20 changes: 20 additions & 0 deletions demos/url-rewrite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict'

const gateway = require('../index')
const PORT = process.env.PORT || 8080

gateway({
routes: [{
pathRegex: '',
prefix: '/customers/:customerId',
target: 'http://localhost:3000',
urlRewrite: ({ params: { customerId } }) => `/users/${customerId}`
}]
}).start(PORT).then(server => {
console.log(`API Gateway listening on ${PORT} port!`)
})

const service = require('restana')({})
service
.get('/users/:id', (req, res) => res.send('Hello ' + req.params.id))
.start(3000).then(() => console.log('Service listening on 3000 port!'))
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ const gateway = (opts) => {

const handler = (route, proxy, proxyHandler) => async (req, res, next) => {
try {
req.url = req.url.replace(route.prefix, route.prefixRewrite)
req.url = route.urlRewrite
? route.urlRewrite(req)
: req.url.replace(route.prefix, route.prefixRewrite)
const shouldAbortProxy = await route.hooks.onRequest(req, res)
if (!shouldAbortProxy) {
const proxyOpts = Object.assign({
Expand Down
2 changes: 1 addition & 1 deletion test/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ module.exports = async () => {
{
pathRegex: '',
prefix: '/endpoint-proxy-methods',
prefixRewrite: '/endpoint-proxy-methods',
urlRewrite: (req) => '/endpoint-proxy-methods',
target: 'http://localhost:3000',
methods: ['GET', 'POST']
},
Expand Down