Code refactoring (s3)

This commit is contained in:
skidoodle 2022-05-03 20:59:45 +02:00
parent 6c649c1c62
commit 4e73740c16

View file

@ -1,7 +1,6 @@
import aws, { ConfigurationOptions } from 'aws-sdk'; import aws from 'aws-sdk';
import { NextApiRequest, NextApiResponse } from 'next'; import { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) { export default async function handler(req: NextApiRequest, res: NextApiResponse) {
aws.config.s3 = ({ aws.config.s3 = ({
accessKeyId: process.env.ACCESS_KEY, accessKeyId: process.env.ACCESS_KEY,
@ -12,19 +11,18 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}); });
const s3 = new aws.S3(); const s3 = new aws.S3();
const params = { const params = {
Bucket: 'i.albrt.hu' Bucket: process.env.BUCKET!,
} }
const data = await s3.listObjectsV2(params).promise() const data = await s3.listObjectsV2(params).promise()
let totalsize = data.Contents!.reduce((acc, curr) => { let size = 0;
return acc + curr.Size! / 1024 / 1024 / 1024 data.Contents!.forEach(item => {
}, 0) size += item.Size! / 1024 / 1024 / 1024;
});
res.setHeader( size = Number(size.toFixed(2));
'Cache-Control', let objects = data.Contents!.length
'public, s-maxage=10, stale-while-revalidate=59' res.setHeader('Cache-Control', 'public, s-maxage=10, stale-while-revalidate=59');
) res.status(200).json(JSON.stringify({
res.status(200).json (JSON.stringify({ object: objects,
'objectCount': data.KeyCount, size: size
'totalSize': (Math.round(totalsize * 100) / 100)
}, null, 2)) }, null, 2))
} }