import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { config } from "../config/index.js";
export const s3Client = new S3Client({
region: config.aws.region,
credentials: {
accessKeyId: config.aws.accessKeyId,
secretAccessKey: config.aws.secretAccessKey,
},
});
const router = express.Router();
router.get("/:id", async (req, res, next) => {
try {
const { id } = req.params;
if (!id) return res.status(400).send();
const command = new GetObjectCommand({
Bucket: config.aws.bucketName,
Key: id,
});
const data = await s3Client.send(command);
let contentType = "image/jpeg";
if (id.endsWith(".webp")) contentType = "image/webp";
else if (id.endsWith(".png")) contentType = "image/png";
res.writeHead(200, {
"Content-Type": contentType,
"cache-control": "max-age=604800, public",
});
data.Body.pipe(res);
} catch (error) {
next(error);
}
});
aws 공식문서 - Amazon S3 examples using SDK for JavaScript (v3)
aws 공식문서 - AWS SDK를 사용하여 Amazon S3 버킷에서 객체 가져오기
@aws-sdk/client-s3 Github
블로그 - aws Access Key 생성 방법