File size: 1,267 Bytes
1a81036 | 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 | import { S3Client, PutObjectCommand, DeleteObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const r2Client = new S3Client({
region: 'auto',
endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
},
});
const BUCKET = process.env.R2_BUCKET_NAME || 'woodlands-supermarket';
const PUBLIC_URL = process.env.R2_PUBLIC_URL || '';
export const uploadToR2 = async (buffer, key, contentType) => {
await r2Client.send(new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: buffer,
ContentType: contentType,
CacheControl: 'public, max-age=31536000',
}));
return {
key,
url: PUBLIC_URL ? `${PUBLIC_URL}/${key}` : `/api/upload/file/${encodeURIComponent(key)}`,
};
};
export const deleteFromR2 = async (key) => {
await r2Client.send(new DeleteObjectCommand({ Bucket: BUCKET, Key: key }));
};
export const getSignedDownloadUrl = async (key, expiresIn = 3600) => {
const command = new GetObjectCommand({ Bucket: BUCKET, Key: key });
return getSignedUrl(r2Client, command, { expiresIn });
};
export default r2Client;
|