Skip to content

Commit

Permalink
fixed #1
Browse files Browse the repository at this point in the history
added possibility to add a new delegate/change an existing delegate so users can change the response body when they want to
  • Loading branch information
daanvanham committed Jun 24, 2016
1 parent 0597916 commit adc746b
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ let defaults = {
'content-type': 'application/json'
},

delegate = {
delegates = {
applicationJson: (result, code, message) => {
let body = {
statusCode: code,
Expand Down Expand Up @@ -67,6 +67,12 @@ class Status {
});
}

addDelegation(type, delegation) {
if (typeof delegation === 'function') {
delegates[type] = delegation;
}
}

/**
* create a function based on the status code message
*
Expand All @@ -84,7 +90,7 @@ class Status {

headers = submerge(headers || {}, defaults);
type = camelcase(headers['content-type'].replace(/\//, ' '));
body = type in delegate ? delegate[type].apply(status, [result, code, message]) : result;
body = type in delegates ? delegates[type].apply(status, [result, code, message]) : result;

return applyHeaders(headers, reply(body).code(code));
};
Expand Down
48 changes: 48 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,51 @@ Object.keys(status).forEach(function(key) {
});
});
});

lab.experiment('add a new delegation', function() {
lab.test('should be skipped if it\'s not a function', function(done) {
var response;

status.addDelegation('textHtml', 'some-text');

response = status.ok.apply(null, [new Reply(), 'Test', {'content-type': 'text/html'}]);

Code.expect(response.result).to.equal('Test');

done();
});

lab.test('should be able to alter the response.result', function(done) {
var response;

status.addDelegation('textHtml', function() {
return 'Hi!';
});

response = status.ok.apply(null, [new Reply(), 'Test', {'content-type': 'text/html'}]);

Code.expect(response.result).to.equal('Hi!');

done();
});

lab.test('should be able to alter an existing delegate', function(done) {
var response;

response = status.ok.apply(null, [new Reply(), ['Test']]);

Code.expect(response.result).to.be.an.object();
Code.expect(response.result.statusCode).to.be.a.number();
Code.expect(response.result.result).to.be.an.array();

status.addDelegation('applicationJson', function(result) {
return result;
});

response = status.ok.apply(null, [new Reply(), ['Test']]);

Code.expect(response.result).to.be.an.array();

done();
});
});

0 comments on commit adc746b

Please sign in to comment.