-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy paths3-helpers.ts
More file actions
72 lines (61 loc) · 1.6 KB
/
s3-helpers.ts
File metadata and controls
72 lines (61 loc) · 1.6 KB
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
import {
GetObjectCommand,
ListObjectsV2Command,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
const s3 = new S3Client({
region: process.env.AWS_REGION || 'eu-west-2',
});
async function uploadToS3(
content: string,
bucket: string,
key: string,
metadata?: Record<string, string>,
): Promise<void> {
await s3.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: content,
Metadata: metadata,
}),
);
}
async function downloadFromS3(
bucket: string,
keyPrefix: string,
): Promise<{ body: string; metadata?: Record<string, string> }> {
const objects = await s3.send(
new ListObjectsV2Command({ Bucket: bucket, Prefix: keyPrefix }),
);
if ((objects.Contents?.length ?? 0) > 1) {
throw new Error(
`Multiple objects found for prefix s3://${bucket}/${keyPrefix}`,
);
}
if ((objects.Contents?.length ?? 0) === 0) {
throw new Error(`No objects found for prefix s3://${bucket}/${keyPrefix}`);
}
const key = objects.Contents?.[0]?.Key;
const response = await s3.send(
new GetObjectCommand({
Bucket: bucket,
Key: key,
}),
);
if (!response.Body) {
throw new Error(`No content found for s3://${bucket}/${key}`);
}
return {
body: await response.Body.transformToString(),
metadata: response.Metadata,
};
}
async function existsInS3(bucket: string, keyPrefix: string): Promise<boolean> {
const objects = await s3.send(
new ListObjectsV2Command({ Bucket: bucket, Prefix: keyPrefix }),
);
return (objects.Contents?.length ?? 0) > 0;
}
export { downloadFromS3, existsInS3, uploadToS3 };