Skip to content

Commit

Permalink
Merge pull request #23 from hapijs/issue-payload-timeout
Browse files Browse the repository at this point in the history
Fix timeouts for multipart payloads
  • Loading branch information
johnbrett committed Nov 14, 2015
2 parents 728d5ed + df8086d commit 19114a9
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,11 @@ internals.Parser.prototype.multipart = function (source, contentType) {
next = Hoek.once(next); // Modify next() for async events
this.next = next;

// Set stream timeout

const clientTimeout = this.settings.timeout;
let clientTimeoutId = null;

const dispenser = new Pez.Dispenser(contentType);

const onError = (err) => {
Expand All @@ -301,6 +306,7 @@ internals.Parser.prototype.multipart = function (source, contentType) {
let data = {};
const finalize = () => {

clearTimeout(clientTimeoutId);
dispenser.removeListener('error', onError);
dispenser.removeListener('part', onPart);
dispenser.removeListener('field', onField);
Expand All @@ -314,6 +320,15 @@ internals.Parser.prototype.multipart = function (source, contentType) {
return next();
};

if (clientTimeout &&
clientTimeout > 0) {

clientTimeoutId = setTimeout(() => {

return next(Boom.clientTimeout());
}, clientTimeout);
}

const set = (name, value) => {

arrayFields = arrayFields || (name.indexOf('[') !== -1);
Expand Down
36 changes: 36 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1467,4 +1467,40 @@ describe('parse()', () => {
});
});
});

it('will timeout correctly for a multipart payload with output as stream', (done) => {

const path = Path.join(__dirname, './file/image.jpg');
const fileStream = Fs.createReadStream(path);

const form = new FormData();
form.append('my_file', fileStream);
form.headers = form.getHeaders();

Subtext.parse(form, null, { parse: true, output: 'stream', timeout: 1 }, (err, parsed) => {

expect(err).to.exist();
expect(err.message).to.equal('Request Timeout');
expect(err.output.statusCode).to.equal(408);
done();
});
});

it('will timeout correctly for a multipart payload with output file', (done) => {

const path = Path.join(__dirname, './file/image.jpg');
const fileStream = Fs.createReadStream(path);

const form = new FormData();
form.append('my_file', fileStream);
form.headers = form.getHeaders();

Subtext.parse(form, null, { parse: true, output: 'file', timeout: 1 }, (err, parsed) => {

expect(err).to.exist();
expect(err.message).to.equal('Request Timeout');
expect(err.output.statusCode).to.equal(408);
done();
});
});
});

0 comments on commit 19114a9

Please sign in to comment.