sky-buckets
Version:
NPM package to redirect file uploads from Multer to MinIO with TypeScript support.
59 lines (58 loc) • 2.54 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MinioStorage = void 0;
exports.createMinioStorage = createMinioStorage;
class MinioStorage {
constructor(opts) {
this._handleFile = async (req, file, cb) => {
try {
const bucketName = await Promise.resolve(this.getBucketName(req, file));
const objectName = await Promise.resolve(this.getObjectName(req, file));
const metadata = this.getMetadata ? await Promise.resolve(this.getMetadata(req, file)) : { 'Content-Type': file.mimetype };
const bucketExists = await this.minioClient.bucketExists(bucketName);
if (!bucketExists) {
await this.minioClient.makeBucket(bucketName, 'us-east-1');
}
const uploadInfo = await this.minioClient.putObject(bucketName, objectName, file.stream, file.size, metadata);
const protocol = this.minioUseSSL ? 'https' : 'http';
const portString = (this.minioUseSSL && this.minioPort === 443) || (!this.minioUseSSL && this.minioPort === 80) ? '' : `:${this.minioPort}`;
cb(null, {
bucket: bucketName,
key: objectName,
etag: uploadInfo.etag,
location: `${protocol}://${this.minioEndPoint}${portString}/${bucketName}/${objectName}`,
originalname: file.originalname,
mimetype: file.mimetype,
size: file.size,
});
}
catch (error) {
cb(error);
}
};
this._removeFile = async (req, file, cb) => {
try {
const bucketName = file.bucket;
const objectName = file.key;
if (bucketName && objectName) {
await this.minioClient.removeObject(bucketName, objectName);
}
cb(null);
}
catch (error) {
cb(error);
}
};
this.minioClient = opts.minioClient;
this.minioEndPoint = opts.minioEndPoint;
this.minioPort = opts.minioPort;
this.minioUseSSL = opts.minioUseSSL;
this.getBucketName = opts.bucketName;
this.getObjectName = opts.objectName;
this.getMetadata = opts.metadata;
}
}
exports.MinioStorage = MinioStorage;
function createMinioStorage(opts) {
return new MinioStorage(opts);
}