-
Notifications
You must be signed in to change notification settings - Fork 234
/
s3.server.ts
50 lines (44 loc) · 1.31 KB
/
s3.server.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
import { PassThrough } from "stream";
import type { UploadHandler } from "@remix-run/node";
import { writeAsyncIterableToWritable } from "@remix-run/node";
import AWS from "aws-sdk";
const { STORAGE_ACCESS_KEY, STORAGE_SECRET, STORAGE_REGION, STORAGE_BUCKET } =
process.env;
if (
!(STORAGE_ACCESS_KEY && STORAGE_SECRET && STORAGE_REGION && STORAGE_BUCKET)
) {
throw new Error(`Storage is missing required configuration.`);
}
const uploadStream = ({ Key }: Pick<AWS.S3.Types.PutObjectRequest, "Key">) => {
const s3 = new AWS.S3({
credentials: {
accessKeyId: STORAGE_ACCESS_KEY,
secretAccessKey: STORAGE_SECRET,
},
region: STORAGE_REGION,
});
const pass = new PassThrough();
return {
writeStream: pass,
promise: s3.upload({ Bucket: STORAGE_BUCKET, Key, Body: pass }).promise(),
};
};
export async function uploadStreamToS3(data: any, filename: string) {
const stream = uploadStream({
Key: filename,
});
await writeAsyncIterableToWritable(data, stream.writeStream);
const file = await stream.promise;
return file.Location;
}
export const s3UploadHandler: UploadHandler = async ({
name,
filename,
data,
}) => {
if (name !== "img") {
return undefined;
}
const uploadedFileLocation = await uploadStreamToS3(data, filename!);
return uploadedFileLocation;
};