@filesrocket/amazons3
Version:
Filerocket service to manage files from Amazon S3
92 lines • 3.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AmazonS3Service = void 0;
const utils_1 = require("@filesrocket/core/lib/utils");
const http_errors_1 = require("http-errors");
const base_1 = require("./base");
class AmazonS3Service extends base_1.BaseAmazonRocket {
constructor(options) {
super(options);
this.createBucket(options.Bucket)
.then((location) => console.log(`Your ${location} bucket was create successfully.`))
.catch((error) => {
if (error.name === 'BucketAlreadyOwnedByYou' || error.name === 'BucketAlreadyExists') {
const { name, message } = error;
return console.warn(`${name}: ${message}`);
}
throw error;
});
}
async create(data, query = {}) {
return new Promise((resolve, reject) => {
const partialQuery = (0, utils_1.omitProps)(query, ['path']);
const callback = (err, file) => {
if (err)
return reject(err);
const { Bucket, Key } = file;
const entity = this.builder(file, { Bucket, Key });
resolve(entity);
};
this.s3.upload({
...partialQuery,
Bucket: query.Bucket || this.options.Bucket,
Key: query.path ? `${query.path}/${data.name}` : data.name,
Body: data.stream
}, callback);
});
}
async list(query = {}) {
var _a;
const partialQuery = (0, utils_1.omitProps)(query, ['path', 'size', 'page', 'prevPage']);
const { Pagination } = this.options;
const paginate = query.size <= Pagination.max
? query.size
: Pagination.default;
const Bucket = query.Bucket || this.options.Bucket;
const data = await this.s3
.listObjectsV2({
...partialQuery,
Bucket,
MaxKeys: paginate,
Prefix: query.path,
ContinuationToken: query.page
})
.promise();
data.Contents = (_a = data.Contents) === null || _a === void 0 ? void 0 : _a.map((item) => {
const Key = item.Key;
return this.builder(item, { Bucket, Key });
});
return this.paginate(data);
}
async get(id, query = {}) {
if (!id)
throw new http_errors_1.BadRequest('Id is empty');
const partialQuery = (0, utils_1.omitProps)(query, ['path']);
const Bucket = query.Bucket || this.options.Bucket;
const payload = {
...partialQuery,
Prefix: id,
Bucket
};
const { Contents = [] } = await this.s3
.listObjectsV2(payload)
.promise();
const items = Contents.map(item => {
const Key = item.Key;
return this.builder(item, { Bucket, Key });
});
const file = items.at(0);
if (!file)
throw new http_errors_1.NotFound('File does not exist');
return file;
}
async remove(id, query = {}) {
const file = await this.get(id, query);
const Bucket = query.Bucket || this.options.Bucket;
const payload = { ...query, Bucket, Key: id };
await this.s3.deleteObject(payload).promise();
return file;
}
}
exports.AmazonS3Service = AmazonS3Service;
//# sourceMappingURL=service.js.map