S3.js (1804B)
1 import { 2 S3Client, 3 PutObjectCommand, 4 HeadObjectCommand, 5 GetObjectCommand, 6 } from "@aws-sdk/client-s3"; 7 import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; 8 9 const makeClient = (cfg) => 10 new S3Client({ 11 region: cfg.region || "us-east-1", 12 endpoint: cfg.endpointUrl ?? undefined, 13 forcePathStyle: cfg.addressingStyle === "path", 14 credentials: 15 cfg.accessKeyId && cfg.secretAccessKey 16 ? { 17 accessKeyId: cfg.accessKeyId, 18 secretAccessKey: cfg.secretAccessKey, 19 } 20 : undefined, 21 }); 22 23 export const uploadToS3Impl = (cfg, key, body, contentType, cb) => () => { 24 const client = makeClient(cfg); 25 const command = new PutObjectCommand({ 26 Bucket: cfg.bucket, 27 Key: key, 28 Body: body, 29 ContentType: contentType, 30 }); 31 32 client 33 .send(command) 34 .then(() => cb(null)()) 35 .catch((err) => cb(err)()); 36 }; 37 38 export const existsInS3Impl = (cfg, key, cb) => () => { 39 const client = makeClient(cfg); 40 const command = new HeadObjectCommand({ 41 Bucket: cfg.bucket, 42 Key: key, 43 }); 44 45 client 46 .send(command) 47 .then(() => cb(null)(true)()) 48 .catch((err) => { 49 if (err.name === "NotFound" || err.$metadata?.httpStatusCode === 404) { 50 cb(null)(false)(); 51 } else { 52 cb(err)(false)(); 53 } 54 }); 55 }; 56 57 export const getPresignedUrlImpl = (cfg, key, cb) => () => { 58 const client = makeClient(cfg); 59 const command = new GetObjectCommand({ 60 Bucket: cfg.bucket, 61 Key: key, 62 }); 63 64 getSignedUrl(client, command, { expiresIn: 86400 }) 65 .then((url) => cb(null)(url)()) 66 .catch((err) => cb(err)("")()); 67 }; 68 69 export const getS3UrlImpl = (cfg, key) => { 70 const endpoint = cfg.endpointUrl || ""; 71 const bucket = cfg.bucket || ""; 72 if (cfg.addressingStyle === "path") { 73 return `${endpoint}/${bucket}/${key}`; 74 } else { 75 return `${endpoint.replace("://", `://${bucket}.`)}/${key}`; 76 } 77 };