-
-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy paths3.tsx
More file actions
67 lines (64 loc) · 1.87 KB
/
s3.tsx
File metadata and controls
67 lines (64 loc) · 1.87 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
import { NextApiRequest, NextApiResponse } from "next";
import AWS from "aws-sdk";
import getConfig from "next/config";
const { serverRuntimeConfig } = getConfig();
export default async (req: NextApiRequest, res: NextApiResponse) => {
const bucket = serverRuntimeConfig.BUCKET;
const key = req.query.key;
const params: AWS.S3.PutObjectRequest = {
Bucket: bucket,
Key: key as string,
};
const client = getClient();
const operation = req.query.operation;
if (operation === "put") {
put(client, params);
} else if (operation === "delete") {
del(client, params);
}
function getClient() {
const region = serverRuntimeConfig.AWS_REGION;
const accessKey = serverRuntimeConfig.AWSACCESSKEYID;
const secretKey = serverRuntimeConfig.AWSSECRETKEY;
AWS.config.update({
accessKeyId: accessKey,
secretAccessKey: secretKey,
signatureVersion: "v4",
region: region,
});
const options = {
signatureVersion: "v4",
region: region,
// uncomment to use accelerated endpoint
// accelerated endpoint must be turned on in your s3 bucket first
// endpoint: new AWS.Endpoint(
// "bucket.s3-accelerate.amazonaws.com"
// ),
// useAccelerateEndpoint: true,
};
const client = new AWS.S3(options);
return client;
}
function put(client: AWS.S3, params: AWS.S3.PutObjectRequest) {
const putParams = {
...params,
Expires: 5 * 60,
};
client.getSignedUrl("putObject", putParams, (err, url) => {
if (err) {
res.json({ success: false, err });
} else {
res.json({ success: true, url });
}
});
}
function del(client: AWS.S3, params: AWS.S3.DeleteObjectRequest) {
client.deleteObject(params, err => {
if (err) {
res.json({ success: false, err });
} else {
res.json({ success: true });
}
});
}
};