-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy paths3.ts
More file actions
105 lines (94 loc) · 2.68 KB
/
s3.ts
File metadata and controls
105 lines (94 loc) · 2.68 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { ReadStream } from "fs";
import { getSignedUrl as getS3SignedUrl } from "@aws-sdk/s3-request-presigner";
import {
S3Client,
PutObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
GetObjectTaggingCommand,
} from "@aws-sdk/client-s3";
import {
cloudEndpoint,
cloudKey,
cloudSecret,
cloudBucket,
cloudRegion,
CLOUDFRONT_KEY_PAIR_ID,
CLOUDFRONT_PRIVATE_KEY,
CDN_MAX_AGE,
CLOUDFRONT_ENDPOINT,
} from "../config/constants";
import { getSignedUrl as getCfSignedUrl } from "@aws-sdk/cloudfront-signer";
export interface UploadParams {
Key: string;
Body: ReadStream;
ContentType: string;
ACL: "private" | "public-read";
Tagging?: string;
}
export interface DeleteParams {
Key: string;
}
export interface PresignedURLParams {
name: string;
mimetype?: string;
}
let s3Client: S3Client | null = null;
const getS3Client = () => {
if (!s3Client) {
s3Client = new S3Client({
region: cloudRegion,
endpoint: cloudEndpoint,
credentials: {
accessKeyId: cloudKey,
secretAccessKey: cloudSecret,
},
});
}
return s3Client;
};
export const putObject = async (params: UploadParams) => {
const command = new PutObjectCommand(
Object.assign({}, { Bucket: cloudBucket }, params),
);
const response = await getS3Client().send(command);
return response;
};
export const deleteObject = async (params: DeleteParams) => {
const command = new DeleteObjectCommand(
Object.assign({}, { Bucket: cloudBucket }, params),
);
const response = await getS3Client().send(command);
return response;
};
export const getObjectTagging = async (params: { Key: string }) => {
const command = new GetObjectTaggingCommand(
Object.assign({}, { Bucket: cloudBucket }, params),
);
const response = await getS3Client().send(command);
return response;
};
export const generateSignedUrl = async (key: string): Promise<string> => {
const command = new GetObjectCommand({
Bucket: cloudBucket,
Key: key,
});
const url = await getS3SignedUrl(getS3Client(), command);
return url;
};
export const generateCDNSignedUrl = (key: string): string => {
if (
!CLOUDFRONT_ENDPOINT ||
!CLOUDFRONT_KEY_PAIR_ID ||
!CLOUDFRONT_PRIVATE_KEY
) {
throw new Error("CDN configuration is missing");
}
const url = getCfSignedUrl({
url: `${CLOUDFRONT_ENDPOINT}/${key}`,
keyPairId: CLOUDFRONT_KEY_PAIR_ID,
privateKey: CLOUDFRONT_PRIVATE_KEY,
dateLessThan: new Date(Date.now() + CDN_MAX_AGE).toISOString(),
});
return url;
};