UNPKG

@cpmech/az-s3

Version:
85 lines (78 loc) 2.4 kB
import { S3 } from 'aws-sdk'; import { name2fileExt, fileExt2contentType } from '@cpmech/util'; // returns the filekeys of those deleted successfully const deleteObjects = async (bucket, filekeys, quiet = true, s3Config) => { const s3 = new S3(s3Config); const res = await s3 .deleteObjects({ Bucket: bucket, Delete: { Objects: filekeys.map(k => ({ Key: k })), Quiet: quiet, }, }) .promise(); const { Deleted } = res; if (!Deleted) { throw new Error('cannot delete objects'); } return Deleted.reduce((acc, curr) => { if (curr.Key) { acc.push(curr.Key); } return acc; }, []); }; // NOTE: the path must have a FileExt const getDownloadUrl = (bucket, path, expireSeconds, s3Config) => { const s3 = new S3(s3Config); return s3.getSignedUrl('getObject', { Bucket: bucket, Key: path, Expires: expireSeconds, }); }; const getStringObject = async (bucket, filekey, s3Config) => { const s3 = new S3(s3Config); const res = await s3 .getObject({ Bucket: bucket, Key: filekey, }) .promise(); if (!res || !res.Body) { throw new Error(`cannot get string object with filekey = ${filekey}`); } return String(res.Body); }; // get upload URL const getUploadUrl = (bucket, filekey, expiresSeconds = 60, s3Config) => { const ext = name2fileExt(filekey); if (!ext) { throw new Error('file extension must be given in filekey'); } const s3 = new S3(s3Config); const url = s3.getSignedUrl('putObject', { Bucket: bucket, Key: filekey, ContentType: fileExt2contentType[ext], Expires: expiresSeconds, }); return url; }; // put data on S3 and returns the filekey // NOTE: the given filekey should have a FileExt const putStringObject = async (data, bucket, filekey, s3Config) => { const ext = name2fileExt(filekey); const s3 = new S3(s3Config); await s3 .putObject({ Bucket: bucket, Key: filekey, Body: data, ContentType: fileExt2contentType[ext], }) .promise(); return filekey; }; export { deleteObjects, getDownloadUrl, getStringObject, getUploadUrl, putStringObject };