This repository has been archived by the owner on Aug 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
smushed.ts
87 lines (77 loc) · 2.24 KB
/
smushed.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* This is the _not_ hexagonal example.
* All concerns are smushed together into one mess.
*/
import {DynamoDB} from "aws-sdk";
import {DocumentClient, PutItemOutput} from "aws-sdk/clients/dynamodb";
import {APIGatewayProxyEvent} from "aws-lambda";
const dynamoClient = new DynamoDB.DocumentClient();
/** Request body for the RESTFul API - ✅ */
export interface PackageRequest {
name: string;
description?: string;
contentType?: string;
fileName?: string;
}
/** Implementation detail right in the name - 🤨 */
export interface DynamoDBPackage extends PackageRequest {
userId: string;
userName: string;
createdOn: string;
ttl?: number;
}
/** AWS Lambda function entry point */
export const handler = async (event: APIGatewayProxyEvent) => {
const request = JSON.parse(event.body || '{}') as PackageRequest;
const claims = event.requestContext.authorizer?.claims || {};
if (!request.name || !request.description || !request.contentType || !request.fileName) {
return {
statusCode: 400,
body: 'Request validation error'
};
}
// 😲: Dealing with DynamoDB details in handler
const tableName = process.env.TABLE_NAME;
const epochTime = Math.floor(Date.now() / 1000);
const entry: DynamoDBPackage = {
...request,
userId: claims.sub || '',
userName: claims.name || '',
createdOn: new Date().toISOString(),
ttl: epochTime + 60
};
try {
await addPackage(dynamoClient, tableName, entry);
return {
statusCode: 200,
body: JSON.stringify(entry)
};
} catch (error) {
if (error.message === 'Name already exists') {
return {
statusCode: 401,
body: error.message
};
}
return {
statusCode: 500,
body: error.message
};
}
};
// 👍: Helper function to update DynamoDB
// 👎: In same file with everything else & returns DynamoDB specific data type that isn't even used.
async function addPackage(
client: DocumentClient,
tableName: string | undefined,
packageUpload: DynamoDBPackage,
): Promise<PutItemOutput> {
if (!tableName) {
throw Error('tableName is not defined');
}
const params: DocumentClient.PutItemInput = {
TableName: tableName,
Item: packageUpload,
};
return client.put(params).promise();
}