-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda-powered-up.ts
70 lines (56 loc) · 2.16 KB
/
lambda-powered-up.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
import { makeIdempotent, IdempotencyConfig } from '@aws-lambda-powertools/idempotency';
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
import { ApiGatewayProxyEvent, ApiGatewayProxyResult } from 'aws-lambda';
import middy from '@middy/core';
const { S3 } = require('aws-sdk');
const s3 = new S3();
// Powertools logger
const logger = new Logger({
serviceName: 's3Uploader', // Especially useful if you use multiple Lambda functions to compose a service
logLevel: 'INFO',
});
// Powertools Idempotency configuration
const persistenceStore = new DynamoDBPersistenceLayer({
tableName: process.env.IDEMPOTENCY_TABLE_NAME || 'tableNotFoundInEnv'
});
const idempotencyConfig = new IdempotencyConfig({
eventKeyJmesPath: 'body',
});
// Main function
async function lambdaHandler (event: ApiGatewayProxyEvent): Promise<ApiGatewayProxyResult> {
try {
const bucketName = process.env.BUCKET_NAME;
if (!bucketName) {
throw new Error('Bucket name not provided. Make sure the environment variable BUCKET_NAME is set.');
}
const requestBody = JSON.parse(event.body);
const message = requestBody.message;
// Get the current date and time in ISO string format
const currentDate = new Date();
const isoStringDate = currentDate.toISOString();
// Use the ISO string as the key for the S3 object
const params = {
Bucket: bucketName,
Key: `powered-up-${isoStringDate}.txt`,
Body: message,
};
await s3.putObject(params).promise();
return {
statusCode: 200,
body: JSON.stringify({ message: `File uploaded successfully with content: '${message}'` }),
};
} catch (error: any) {
return {
statusCode: 500,
body: JSON.stringify({ message: 'Error uploading file to S3: ' + error.message }),
};
}
};
// Apply the idempotency middleware
export const handler = makeIdempotent(
// Injecting Lambda context in the handler, to be used in the logs
middy(lambdaHandler)
.use(injectLambdaContext(logger, { logEvent: true })),
{ persistenceStore, config: idempotencyConfig }
);