Skip to content

Commit

Permalink
feat: Set a default body
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Krems committed May 13, 2019
1 parent 4512c2b commit 987d61c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/respond.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ function isBody(value) {
return value === null || isData(value) || isStream(value) || isLazy(value);
}

function getDefaultBody() {
return '';
}

class VirtualResponse extends PassThrough {
constructor({ statusCode = 200, headers = {}, body }) {
super();
Expand All @@ -65,7 +69,11 @@ class VirtualResponse extends PassThrough {
this.cachedError = null;

httpify(this, headers);
if (isBody(body)) this.body(body);
if (isBody(body)) {
this.body(body);
} else {
this.bodyFactory = getDefaultBody.bind(null, this);
}
}

error(e) {
Expand All @@ -89,8 +97,10 @@ class VirtualResponse extends PassThrough {
this.bodyFactory = body;
return this;
}
this.bodyFactory = null;

if (typeof body === 'string') body = Buffer.from(body);
if (body === null) body = Buffer.alloc(0);

if (body instanceof Buffer) {
this.body = body;
Expand Down
14 changes: 14 additions & 0 deletions test/integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ function handler(req) {
case '/ok':
return respond().body('ok');

case '/redirect':
return respond({
statusCode: 302,
headers: { Location: '/post-redirect' },
});

case '/post-redirect':
return respond({ statusCode: 201 }).body('redirected');

case '/invalid':
return respond()
.body('invalid')
Expand Down Expand Up @@ -65,6 +74,11 @@ describe('quinn:integration', () => {
itSends('ok');
});

describeRequest('GET', '/redirect', () => {
assertStatusCode(201);
itSends('redirected');
});

describeRequest('GET', '/file-stream', () => {
assertStatusCode(200);
itSends('--recursive\n');
Expand Down

0 comments on commit 987d61c

Please sign in to comment.