Skip to content

Instantly share code, notes, and snippets.

@leegilmorecode
Created August 12, 2021 08:03
Show Gist options
  • Save leegilmorecode/437c54f37e54384acdb0274f1f21007f to your computer and use it in GitHub Desktop.
Save leegilmorecode/437c54f37e54384acdb0274f1f21007f to your computer and use it in GitHub Desktop.
Example code for generating a pre-signed upload URL using AWS S3
import AWS from 'aws-sdk';
import { APIGatewayProxyHandler, APIGatewayProxyResult, APIGatewayEvent } from 'aws-lambda';
import { v4 as uuid } from 'uuid';
import config from '../../config';
const METHOD = 'upload-file.handler';
const s3 = new AWS.S3();
export const handler: APIGatewayProxyHandler = async ({
pathParameters,
}: APIGatewayEvent): Promise<APIGatewayProxyResult> => {
try {
const correlationId = uuid();
console.log(`${correlationId} - ${METHOD} - started`);
// basic validation to check id exists, but in reality you would
// validate the inputs using an approach like json schema
if (!pathParameters?.id) throw new Error('path parameter id does not exist');
const { id } = pathParameters;
const imageName = `${id}.png`;
console.log(`${correlationId} - ${METHOD} - bucket: ${config.bucket}, file: ${imageName}`);
// create an s3 upload url for the image
const url = s3.getSignedUrl('putObject', {
Bucket: config.bucket,
Key: `${imageName}`,
Expires: 60,
});
// you would NEVER log this but we are doing it for clarity of the logs for the demo
console.log(`${correlationId} - ${METHOD} - generated url: ${url}`);
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify(
{
url,
},
null,
2,
),
};
} catch (error: any) {
console.error(`${METHOD} - error: ${JSON.stringify(error)}`);
return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify('An error has occurred', null, 2),
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment