39 lines
1.2 KiB
JavaScript
39 lines
1.2 KiB
JavaScript
"use strict";
|
|
const { ROOT_PATH, LIB_PATH, MODELS_PATH, API_CONFIG } = process.env;
|
|
const apiConfig = require( `${ROOT_PATH}/${API_CONFIG}` );
|
|
|
|
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
const s3Client = new S3Client({
|
|
region : apiConfig.S3.region,
|
|
credentials : {
|
|
accessKeyId : apiConfig.S3.accessKeyId,
|
|
secretAccessKey : apiConfig.S3.secretAccessKey
|
|
}
|
|
});
|
|
const s3Bucket = apiConfig.S3.bucket;
|
|
const s3BucketKey = apiConfig.S3.key;
|
|
|
|
async function downloadFile( bucket, key, obj_id ){
|
|
const params = {
|
|
Bucket: bucket,
|
|
Key : `${key}/${obj_id}`
|
|
};
|
|
const s3resp = await s3Client.send( new GetObjectCommand( params ) );
|
|
const chunks = []
|
|
for await (const chunk of s3resp.Body) {
|
|
chunks.push(chunk)
|
|
}
|
|
const body = Buffer.concat(chunks);
|
|
s3resp.Body = body;
|
|
return s3resp;
|
|
}
|
|
const getAttachmentFile = async(req, res) => {
|
|
const attachmentId = req.params.id;
|
|
const file = await downloadFile( s3Bucket, s3BucketKey, attachmentId );
|
|
res.attachment( attachmentId );
|
|
res.setHeader('Content-Type', file.ContentType );
|
|
res.send( file.Body );
|
|
}
|
|
|
|
module.exports = { getAttachmentFile };
|