@occupop/lib-s3-storage
Version:
Tiny S3 storage helper (AWS & LocalStack) with injectable bucket, signed URLs and public URLs.
110 lines • 4.28 kB
JavaScript
// src/s3-storage.ts
import { GetObjectCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl as presign } from "@aws-sdk/s3-request-presigner";
import crc32 from "crc-32";
var createS3Storage = (cfg) => {
const isLocal = !!cfg.endpoint && /localstack/i.test(cfg.endpoint);
const accelerate = !isLocal && !!cfg.accelerate;
const region = cfg.region;
const defaultBucket = cfg.defaultBucket ?? "";
const defaultExpires = cfg.defaultExpiresInSeconds ?? 180;
const publicMode = cfg.publicUrlMode ?? "raw";
const publicAcl = !!cfg.publicAcl;
const cacheControl = cfg.cacheControl ?? "private, max-age=0, no-cache";
const client = new S3Client({
region: cfg.region,
credentials: cfg.credentials,
...cfg.endpoint && { endpoint: cfg.endpoint },
...typeof cfg.forcePathStyle !== "undefined" && { forcePathStyle: cfg.forcePathStyle },
...cfg.accelerate && { useAccelerateEndpoint: true }
});
const pickBucket = (override) => {
const b = (override ?? defaultBucket).trim();
if (!b) throw new Error("Bucket is required");
return b;
};
const normalizeKey = (bucket, raw) => raw.replace(/^\/+/, "").replace(/\/{2,}/g, "/").replace(`${bucket}/`, "");
const encodeKeyPath = (k) => k.split("/").map(encodeURIComponent).join("/");
const buildRawUrl = (bucket, key) => {
const encoded = encodeKeyPath(key);
if (isLocal && cfg.endpoint) {
return `${cfg.endpoint.replace(/\/$/, "")}/${bucket}/${encoded}`;
}
if (accelerate) {
return `https://${bucket}.s3-accelerate.amazonaws.com/${encoded}`;
}
return `https://${bucket}.s3.${region}.amazonaws.com/${encoded}`;
};
const crc32Base64 = (buf) => {
const signed = crc32.buf(buf) >>> 0;
const b = Buffer.alloc(4);
b.writeUInt32BE(signed, 0);
return b.toString("base64");
};
const contentDisposition = (fileName) => fileName ? `inline; filename="${encodeURIComponent(fileName)}"` : void 0;
const getSignedPutUrl = async (input) => {
const bucket = pickBucket(input.bucket);
const key = normalizeKey(bucket, input.path);
const expiresIn = input.expiresInSeconds ?? defaultExpires;
const cmd = new PutObjectCommand({
Bucket: bucket,
Key: key,
ContentType: input.contentType,
// ContentDisposition: contentDisposition(input.fileName),
...input.checksumCRC32Base64 ? { ChecksumCRC32: input.checksumCRC32Base64 } : {}
});
const url = await presign(client, cmd, { expiresIn });
return { url, bucket, key, expiresIn };
};
const putObject = async (input) => {
const bucket = pickBucket(input.bucket);
const key = normalizeKey(bucket, input.path);
const body = Buffer.from(input.bodyBase64, "base64");
const checksum = crc32Base64(body);
const commandInput = {
Bucket: bucket,
Key: key,
Body: body,
ContentType: input.contentType,
// ContentDisposition: contentDisposition(input.fileName),
CacheControl: input.cacheControl ?? cacheControl,
ChecksumCRC32: checksum,
...publicAcl ? { ACL: "public-read" } : {}
};
const command = new PutObjectCommand(commandInput);
await client.send(command);
const url = publicMode === "signed" ? (await getSignedGetUrl({ path: key, bucket })).url : buildRawUrl(bucket, key);
return { url, bucket, key };
};
const getSignedGetUrl = async ({
path,
bucket,
expiresInSeconds
}) => {
const b = pickBucket(bucket);
const key = normalizeKey(b, path);
const expiresIn = expiresInSeconds ?? defaultExpires;
const cmd = new GetObjectCommand({ Bucket: b, Key: key });
const url = await presign(client, cmd, { expiresIn });
return { url, bucket: b, key, expiresIn };
};
const getPublicUrl = async (input) => {
const bucket = pickBucket(input.bucket);
const key = normalizeKey(bucket, input.path);
const mode = input.mode ?? publicMode;
if (mode === "signed") {
return (await getSignedGetUrl({ path: key, bucket, expiresInSeconds: input.expiresInSeconds ?? 300 })).url;
}
return buildRawUrl(bucket, key);
};
return {
getSignedPutUrl,
putObject,
getPublicUrl,
getSignedGetUrl
};
};
export {
createS3Storage
};
//# sourceMappingURL=index.js.map