MusicTopus/src/libs/aws.js

73 lines
1.6 KiB
JavaScript
Raw Normal View History

import AWS from "aws-sdk";
import fs from "fs";
import path from "path";
import axios from "axios";
import { v4 as uuid } from "uuid";
import {
awsAccessKeyId,
awsSecretAccessKey,
s3BaseFolder,
s3Endpoint,
s3Bucket,
s3Signature,
} from "../config";
AWS.config.update({
accessKeyId: awsAccessKeyId,
secretAccessKey: awsSecretAccessKey,
});
/**
* Fonction permettant de stocker un fichier local sur S3
* @param {String} filename
* @param {String} file
* @param {Boolean} deleteFile
*
* @return {String}
*/
export const uploadFromFile = async (filename, file, deleteFile = false) => {
const data = await fs.readFileSync(file);
const base64data = Buffer.from(data, "binary");
const dest = path.join(s3BaseFolder, filename);
const s3 = new AWS.S3({
endpoint: s3Endpoint,
signatureVersion: s3Signature,
});
await s3
.putObject({
Bucket: s3Bucket,
Key: dest,
Body: base64data,
ACL: "public-read",
})
.promise();
if (deleteFile) {
fs.unlinkSync(file);
}
return `https://${s3Bucket}.${s3Endpoint}/${dest}`;
};
/**
* Fonction permettant de stocker un fichier provenant d'une URL sur S3
* @param {String} url
*
* @return {String}
*/
export const uploadFromUrl = async (url) => {
const filename = `${uuid()}.jpg`;
const file = `/tmp/${filename}`;
const { data } = await axios.get(url, { responseType: "arraybuffer" });
fs.writeFileSync(file, data);
return uploadFromFile(filename, file, true);
// return s3Object;
};