Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/lambda_api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ The LambdaAPI does not throws error. If any error happens within any handler, it

## HEAD request

Requests using HTTP verb `HEAD` are handled different, they don't try to match handlers, they will always return `204 <empty>`.
Requests using HTTP verb `HEAD` are handled different by default: if no handler is registered for `HEAD`, they will always return `204 <empty>` without trying to match any other handler.

If you register a handler for `HEAD` (via `.addHandler( { method: 'HEAD', ... } )`), it takes precedence and is invoked normally, just like any other verb.

## Constructor

Expand Down
8 changes: 4 additions & 4 deletions src/lambda_api/lambda_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@ export class LambdaApi {
const event = new Event( { transform: this.#transformRequest } );
event.parseFromAwsEvent( awsEvent );

if ( event.method === 'HEAD' ) {
return this.#apiResponse.setContent( 204 ).toJSON();
}

const handler = this.#handlers.find( h => h.match( event ) );
if ( !handler ) {
if ( event.method === 'HEAD' ) {
return this.#apiResponse.setContent( 204 ).toJSON();
}

return this.#apiResponse.setContent( 405, Text.ERROR_405 ).toJSON();
}

Expand Down
33 changes: 33 additions & 0 deletions src/lambda_api/lambda_api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,4 +268,37 @@ describe( 'Api Spec', () => {
strictEqual( control.mock.calls.length, 0 );
} );
} );

describe( 'HEAD request', () => {
const headEvent = {
version: '2.0',
requestContext: {
http: {
method: 'HEAD',
path: '/'
}
}
};

it( 'Should return HTTP 204 by default when no handler is registered for HEAD', async () => {
const api = new LambdaApi();
api.addHandler( { method: 'GET', fn: _ => 200 } );

const result = await api.process( headEvent );
partialDeepStrictEqual( result, { statusCode: 204 } );
} );

it( 'Should invoke a registered HEAD handler instead of the default response', async () => {
const api = new LambdaApi();
api.addHandler( { method: 'HEAD', fn: _ => [ 200, '', { 'Content-Length': '42' } ] } );

const result = await api.process( headEvent );
partialDeepStrictEqual( result, {
statusCode: 200,
headers: {
'Content-Length': '42'
}
} );
} );
} );
} );