-
-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathinstallUploadRouter.ts
More file actions
57 lines (54 loc) · 1.59 KB
/
Copy pathinstallUploadRouter.ts
File metadata and controls
57 lines (54 loc) · 1.59 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
import { Express, Router } from "express";
import uuidv4 from "uuid/v4";
import * as aws from "aws-sdk";
import {
awsRegion,
uploadBucket,
uploadBucketPublicUrlPrefix,
} from "@app/config";
interface Options {
preserveFileName?: boolean;
prefix?: string;
}
function makeUploadRouter({ preserveFileName, prefix }: Options = {}) {
const router = Router();
router.get("/signedUrl", async (req, res) => {
const contentType = req.query.contentType
? String(req.query.contentType)
: undefined;
const fileName =
req.query.fileName && preserveFileName
? String(req.query.fileName)
: uuidv4();
const fileKey = prefix ? prefix + fileName : fileName;
const publicUrlPrefix =
uploadBucketPublicUrlPrefix ||
`https://${uploadBucket}.s3.amazonaws.com/`;
const s3 = new aws.S3({
region: awsRegion,
signatureVersion: "v4",
});
const params = {
Bucket: uploadBucket,
Key: fileKey,
ContentType: contentType,
Expires: 60, // signed URL will expire in 60 seconds
ACL: "public-read", // uploaded file will be publicly readable
};
try {
const signedUrl = await s3.getSignedUrlPromise("putObject", params);
return res.json({
signedUrl,
publicUrl: publicUrlPrefix + fileKey,
});
} catch (err) {
console.log(err);
return res.status(500).send("Cannot create S3 signed URL");
}
});
return router;
}
export default async function installUploadRouter(app: Express) {
const router = makeUploadRouter({ preserveFileName: true });
app.use("/upload", router);
}