Skip to content

Commit

Permalink
Do not overwrite headers of StructuredReturn (#288)
Browse files Browse the repository at this point in the history
* Do not overwrite headers of StructuredReturn
* Improve check for user-provided headers
  • Loading branch information
fc7 authored Jul 26, 2023
1 parent 97258a0 commit a2c37a1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
11 changes: 7 additions & 4 deletions lib/invoker.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,13 @@ module.exports = function invoker(func) {

// Check for user supplied body
if (fnReturn.body !== undefined) {
if (typeof fnReturn.body === 'string') {
payload.headers['content-type'] = 'text/plain; charset=utf8';
} else if (typeof fnReturn.body === 'object') {
payload.headers['content-type'] = 'application/json; charset=utf8';
// Provide default content-type unless supplied by user
if (!payload.headers || !payload.headers['content-type']) {
if (typeof fnReturn.body === 'string') {
payload.headers['content-type'] = 'text/plain; charset=utf8';
} else if (typeof fnReturn.body === 'object') {
payload.headers['content-type'] = 'application/json; charset=utf8';
}
}
payload.response = fnReturn.body;
} else if (typeof fnReturn === 'object' && !fnReturn?.body) {
Expand Down
9 changes: 9 additions & 0 deletions test/fixtures/response-structured/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = function() {
return {
headers: {
'Content-Type': 'image/jpeg'
},
body: Buffer.from([0xd8, 0xff, 0xe0, 0xff, 0x10, 0x00, 0x46]),
statusCode: 201,
};
};
19 changes: 19 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -589,3 +589,22 @@ test('Reads a func.yaml file for logLevel', t => {
});
}, errHandler(t));
});

test('Handles HTTP response provided as StructuredReturn', t => {
const func = require(`${__dirname}/fixtures/response-structured/`);
start(func)
.then(server => {
t.plan(3);
request(server)
.get('/')
.expect(201)
.expect('Content-Type', /jpeg/)
.end((err, res) => {
t.error(err, 'No error');
t.equal(typeof res.body, 'object');
t.ok(Buffer.isBuffer(res.body), 'body is a buffer');
t.end();
server.close();
});
}, errHandler(t));
});

0 comments on commit a2c37a1

Please sign in to comment.