Skip to content

Commit

Permalink
Merge pull request #183 from humanmade/return-404-non-existent-file
Browse files Browse the repository at this point in the history
Return 404 for non-existent file
  • Loading branch information
jerico authored Mar 18, 2024
2 parents 2e73546 + c8bd83f commit de6067b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
23 changes: 22 additions & 1 deletion src/lambda-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,31 @@ const streamify_handler: StreamifyHandler = async ( event, response ) => {
delete args.presign;
}

let s3_response = await getS3File( config, key, args );
let s3_response;

try {
s3_response = await getS3File( config, key, args );
} catch ( e: any ) {
// An AccessDenied error means the file is either protected, or doesn't exist.
if ( e.Code === 'AccessDenied' ) {
const metadata = {
statusCode: 404,
headers: {
'Content-Type': 'text/html',
},
};
response = awslambda.HttpResponseStream.from( response, metadata );
response.write( 'File not found.' );
response.end();
return;
}
throw e;
}

if ( ! s3_response.Body ) {
throw new Error( 'No body in file.' );
}

let buffer = Buffer.from( await s3_response.Body.transformToByteArray() );

let { info, data } = await resizeBuffer( buffer, args );
Expand Down
7 changes: 3 additions & 4 deletions tests/test-lambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@ test( 'Test content type headers', async () => {
expect( testResponseStream.contentType ).toBe( 'image/gif' );
} );

// Currently the handler will throw an error if the file is not found, rather than correctly
// return a status code and message.
test.failing( 'Test image not found', async () => {
test( 'Test image not found', async () => {
const testResponseStream = new TestResponseStream();
animatedGifLambdaEvent.rawPath = '/tachyon/does-not-exist.gif';

await handler( animatedGifLambdaEvent, testResponseStream );

expect( testResponseStream.contentType ).toBe( 'image/gif' );
expect( testResponseStream.metadata.statusCode ).toBe( 404 );
expect( testResponseStream.contentType ).toBe( 'text/html' );
} );

/**
Expand Down

0 comments on commit de6067b

Please sign in to comment.