|
| 1 | +const StorageSystem = require('./storage-system'); |
| 2 | +const AWS = require('aws-sdk'); |
| 3 | +const fs = require('fs'); |
| 4 | + |
| 5 | +class S3StorageSystem extends StorageSystem { |
| 6 | + constructor(Region) { |
| 7 | + super(); |
| 8 | + this.Region = Region; |
| 9 | + AWS.config.update({region: this.Region}); |
| 10 | + this.s3 = new AWS.S3({apiVersion: '2006-03-01'}); |
| 11 | + } |
| 12 | + |
| 13 | + async deleteBucket(bucketName) { |
| 14 | + this.s3.deleteBucket({Bucket: bucketName}, function (err, data) { |
| 15 | + if (err) { |
| 16 | + return err |
| 17 | + } else { |
| 18 | + return data |
| 19 | + } |
| 20 | + }); |
| 21 | + } |
| 22 | + |
| 23 | + async listBuckets() { |
| 24 | + // Call S3 to list the buckets |
| 25 | + this.s3.listBuckets(function (err, data) { |
| 26 | + if (err) { |
| 27 | + return err |
| 28 | + } else { |
| 29 | + return data.Buckets; |
| 30 | + } |
| 31 | + }); |
| 32 | + } |
| 33 | + |
| 34 | + async listFiles(bucketName) { |
| 35 | + // Call S3 to obtain a list of the objects in the bucket |
| 36 | + this.s3.listObjects({Bucket: bucketName}, function (err, data) { |
| 37 | + if (err) { |
| 38 | + return err |
| 39 | + } else { |
| 40 | + return data |
| 41 | + } |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + async createBucket(bucketName, ACL) { |
| 46 | + // call S3 to create the bucket |
| 47 | + this.s3.createBucket({Bucket: bucketName, ACL: ACL}, function (err, data) { |
| 48 | + if (err) { |
| 49 | + return (err); |
| 50 | + } else { |
| 51 | + return (data.Location); |
| 52 | + } |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + async upload(bucketName, filename, key) { |
| 57 | + fs.readFile(filename, (err, data) => { |
| 58 | + if (err) throw err; |
| 59 | + this.s3.upload({Bucket: bucketName, Key: key, Body: JSON.stringify(data, null, 2)}, function (s3Err, data) { |
| 60 | + if (s3Err) throw s3Err; |
| 61 | + return (`File uploaded successfully at ${data.Location}`) |
| 62 | + }); |
| 63 | + }); |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | + /** |
| 68 | + * @memberof GoogleCloudStorageSystem |
| 69 | + * @name Download |
| 70 | + * @params filename, destination |
| 71 | + * @description Serves as General Download SDK for GCLOUD Storage |
| 72 | + */ |
| 73 | + async download(bucketName, filename, destination) { |
| 74 | + this.s3.getObject({Bucket: bucketName, Key: filename}, (err, data) => { |
| 75 | + if (err) console.error(err); |
| 76 | + fs.writeFileSync(destination, data.Body.toString()); |
| 77 | + return (`${filename} has been Downloaded!`); |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + async deleteFile(buckName, filename) { |
| 82 | + this.s3.deleteObject({Bucket: buckName, Key: filename}, function (err, data) { |
| 83 | + if (err) return (err.stack); // an error occurred |
| 84 | + else return (data); // successful response |
| 85 | + }); |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +module.exports = S3StorageSystem; |
0 commit comments