modern-valhalla
Version:
Private npm repository server
68 lines (52 loc) • 1.47 kB
JavaScript
const AWS = require('mock-aws-s3');
const fs = require('fs');
const {getFileInfo} = require('./s3-utils');
class S3Client {
constructor(config) {
AWS.config.basePath = './buckets';
const cfg = config.s3 || {};
this.bucket = cfg.bucket || 'packages';
this.client = AWS.S3({ // eslint-disable-line new-cap
params: {Bucket: this.bucket},
});
}
getFileStream(fileName) {
const params = {
Bucket: this.bucket,
Key: fileName,
};
return this.client.getObject(params).createReadStream();
}
putFile(filePath, fileName, isPrivate, callback) {
fs.readFile(filePath, (err, fileContent) => {
if (err) {
return callback(err);
}
this.putFileContent(fileContent, fileName, isPrivate, callback);
});
}
putFileContent(fileContent, fileName, isPrivate, callback) {
const fileInfo = getFileInfo(fileName);
const obj = {
Bucket: this.bucket,
Key: fileName,
Body: fileContent,
Expires: new Date(new Date().setYear(new Date().getFullYear() + 1)),
};
if (fileInfo.mimeType) {
obj.ContentType = fileInfo.mimeType;
}
if (fileInfo.gzip) {
obj.ContentEncoding = 'gzip';
}
this.client.putObject(obj, callback);
}
deleteFile(fileName, callback) {
const params = {
Bucket: this.bucket,
Key: fileName,
};
this.client.deleteObject(params, callback);
}
}
module.exports = S3Client;