Skip to content

Commit

Permalink
Merge pull request #5 from sirensolutions/issue-2145
Browse files Browse the repository at this point in the history
Discontinue modifyResponse in favour of onResponse (the library default function)
  • Loading branch information
szydan authored Apr 7, 2017
2 parents bfc5ecf + 734ef83 commit c9bf48e
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 111 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,14 @@ server.route({
});
```
### Custom `uri` template values

When using the `uri` option, there are optional **default** template values that can be injected from the incoming `request`:

* `{protocol}`
* `{host}`
* `{port}`
* `{path}`

```javascript
server.route({
method: 'GET',
Expand Down Expand Up @@ -161,7 +161,7 @@ server.route({
```
**Note** The default variables of `{protocol}`, `{host}`, `{port}`, `{path}` take precedence - it's best to treat those as reserved when naming your own `request.params`.


### Using the `mapUri` and `onResponse` options

Setting both options with custom functions will allow you to map the original request to an upstream service and to processing the response from the upstream service, before sending it to the client. Cannot be used together with `host`, `port`, `protocol`, or `uri`.
Expand All @@ -177,7 +177,7 @@ server.route({
console.log('doing some aditional stuff before redirecting');
callback(null, 'https://some.upstream.service.com/');
},
onResponse: function (err, res, request, reply, settings, ttl) {
onResponse: function (err, res, request, reply, settings, ttl, data) {

console.log('receiving the response from the upstream.');
Wreck.read(res, { json: true }, function (err, payload) {
Expand Down
48 changes: 11 additions & 37 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ internals.schema = Joi.object({
maxSockets: Joi.number().positive().allow(false),

// added for kibi
modifyPayload: Joi.any(),
modifyResponse: Joi.any()
onBeforeSendRequest: Joi.any()
})
.xor('host', 'mapUri', 'uri')
.without('mapUri', 'port', 'protocol')
Expand Down Expand Up @@ -79,8 +78,8 @@ internals.handler = function (route, handlerOptions) {
const settings = Hoek.applyToDefaultsWithShallow(internals.defaults, handlerOptions, ['agent']);
settings.mapUri = handlerOptions.mapUri || internals.mapUri(handlerOptions.protocol, handlerOptions.host, handlerOptions.port, handlerOptions.uri);

const modifyPayload = handlerOptions.modifyPayload || false;
const modifyResponse = handlerOptions.modifyResponse || false;
// kibi: added
const onBeforeSendRequest = handlerOptions.onBeforeSendRequest || false;

if (settings.ttl === 'upstream') {
settings._upstreamTtl = true;
Expand Down Expand Up @@ -146,20 +145,6 @@ internals.handler = function (route, handlerOptions) {
options.headers['content-type'] = contentType;
}


const _sendResponse = function (res, ttl, data) {

let r;
if (data && data.body) {
r = reply(data.body).header('content-type', 'application/json');
} else {
r = reply(res);
}
r.ttl(ttl)
.code(res.statusCode)
.passThrough(!!settings.passThrough); // Default to false
};

const _onError = function (err, res, ttl) {

if (settings.onResponse) {
Expand All @@ -177,7 +162,7 @@ internals.handler = function (route, handlerOptions) {

if (err) {
if (settings.onResponse) {
return settings.onResponse.call(bind, err, res, request, reply, settings, ttl);
return settings.onResponse.call(bind, err, res, request, reply, settings, ttl, data);
}
return reply(err);
}
Expand All @@ -193,30 +178,19 @@ internals.handler = function (route, handlerOptions) {
}

if (settings.onResponse) {
return settings.onResponse.call(bind, null, res, request, reply, settings, ttl);
return settings.onResponse.call(bind, null, res, request, reply, settings, ttl, data);
}

if (modifyResponse) {
modifyResponse(res, data).then((ret) => {

_sendResponse(ret.response, ttl, ret.data);
}).catch((err) => {

let msg = 'Failed request';
if (err.message) {
msg = err.message;
}
return _onError(Boom.badRequest(msg, err));
});
} else {
_sendResponse(res, ttl);
}
return reply(res)
.ttl(ttl)
.code(res.statusCode)
.passThrough(!!settings.passThrough); // Default to false
});
};

// Send request
if (modifyPayload) {
modifyPayload(request).then((payloadAndData) => {
if (onBeforeSendRequest) {
onBeforeSendRequest(request).then((payloadAndData) => {

options.payload = payloadAndData.payload;
_sendRequest(payloadAndData.data);
Expand Down
109 changes: 39 additions & 70 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,46 +78,39 @@ describe('H2o2', () => {
kibi_proxy: {
host: 'localhost',
port: upstream.info.port,
modifyPayload: (request) => {
onBeforeSendRequest: (request) => {

const req = request.raw.req;
return new Promise((fulfill, reject) => {

const chunks = [];
req.on('error', reject);
req.on('data', (chunk) => {
Wreck.read(req, null, (error, payload) => {

chunks.push(chunk);
});
req.on('end', () => {
if (error) {
reject(error);
}

const body = JSON.parse(Buffer.concat(chunks));
const body = JSON.parse(payload.toString());
body.copy = body.msg;
const buffer = new Buffer(JSON.stringify(body));
fulfill({ data: 'connor', payload: buffer });
fulfill({ data: 'connor', payload: new Buffer(JSON.stringify(body)) });
});
});
},
modifyResponse: (response, data) => {
onResponse: (error, response, request, reply, settings, ttl, data) => {

return new Promise((fulfill, reject) => {
if (error) {
reply(error);
}

const chunks = [];
response.on('error', reject);
response.on('data', (d) => {
Wreck.read(response, null, (err, payload) => {

chunks.push(d);
});
response.on('end', () => {

const body = JSON.parse(Buffer.concat(chunks).toString());
body.copy = body.copy.toUpperCase();
body.john = data;
fulfill({
response,
data: { body: new Buffer(JSON.stringify(body)) }
});
});
if (err) {
reply(err);
}

const body = JSON.parse(payload.toString());
body.copy = body.copy.toUpperCase();
body.john = data;
reply(new Buffer(JSON.stringify(body)));
});
}
}
Expand All @@ -137,7 +130,7 @@ describe('H2o2', () => {
});
});

it('modifyPayload the request with error', { parallel: false }, (done) => {
it('onBeforeSendRequest the request with error', { parallel: false }, (done) => {

const dataHandler = function (request, reply) {

Expand All @@ -157,42 +150,18 @@ describe('H2o2', () => {
kibi_proxy: {
host: 'localhost',
port: upstream.info.port,
modifyPayload: (request) => {
onBeforeSendRequest: (request) => {

const req = request.raw.req;
return new Promise((fulfill, reject) => {

const chunks = [];
req.on('error', reject);
req.on('data', (chunk) => {

chunks.push(chunk);
});
req.on('end', () => {
Wreck.read(req, null, (error, payload) => {

reject({ message: 'some error' });
});
});
},
modifyResponse: (response, data) => {

return new Promise((fulfill, reject) => {
if (error) {
reject(error);
}

const chunks = [];
response.on('error', reject);
response.on('data', (d) => {

chunks.push(d);
});
response.on('end', () => {

const body = JSON.parse(Buffer.concat(chunks).toString());
body.copy = body.copy.toUpperCase();
body.john = data;
fulfill({
response,
data: { body: new Buffer(JSON.stringify(body)) }
});
reject(new Error('some error'));
});
});
}
Expand All @@ -215,7 +184,7 @@ describe('H2o2', () => {
});
});

it('modifyResponse the request with error', { parallel: false }, (done) => {
it('onResponse the request with error', { parallel: false }, (done) => {

const dataHandler = function (request, reply) {

Expand All @@ -235,7 +204,7 @@ describe('H2o2', () => {
kibi_proxy: {
host: 'localhost',
port: upstream.info.port,
modifyPayload: (request) => {
onBeforeSendRequest: (request) => {

const req = request.raw.req;
return new Promise((fulfill, reject) => {
Expand All @@ -255,20 +224,20 @@ describe('H2o2', () => {
});
});
},
modifyResponse: (response, data) => {
onResponse: (error, response, request, reply, settings, ttl, data) => {

return new Promise((fulfill, reject) => {
if (error) {
return reply(err);
}

const chunks = [];
response.on('error', reject);
response.on('data', (d) => {
response.on('error', (err) => {

chunks.push(d);
});
response.on('end', () => {
return reply(err);
});
response.on('data', (chunk) => {});
response.on('end', () => {

reject({ message: 'some error' });
});
return reply(Boom.badRequest('some error', new Error()));
});
}
}
Expand Down

0 comments on commit c9bf48e

Please sign in to comment.