|
| 1 | +// S3Adapter |
| 2 | +// |
| 3 | +// Stores Parse files in AWS S3. |
| 4 | + |
| 5 | +import * as AWS from 'aws-sdk'; |
| 6 | +import { FilesAdapter } from './FilesAdapter'; |
| 7 | + |
| 8 | +const DEFAULT_S3_REGION = "us-east-1"; |
| 9 | +const DEFAULT_S3_BUCKET = "parse-files"; |
| 10 | + |
| 11 | +export class S3Adapter extends FilesAdapter { |
| 12 | + // Creates an S3 session. |
| 13 | + // Providing AWS access and secret keys is mandatory |
| 14 | + // Region and bucket will use sane defaults if omitted |
| 15 | + constructor(accessKey, secretKey, options = {}) { |
| 16 | + super(); |
| 17 | + |
| 18 | + this._region = options.region || DEFAULT_S3_REGION; |
| 19 | + this._bucket = options.bucket || DEFAULT_S3_BUCKET; |
| 20 | + this._bucketPrefix = options.bucketPrefix || ''; |
| 21 | + this._directAccess = options.directAccess || false; |
| 22 | + |
| 23 | + let s3Options = { |
| 24 | + accessKeyId: accessKey, |
| 25 | + secretAccessKey: secretKey, |
| 26 | + params: { Bucket: this._bucket } |
| 27 | + }; |
| 28 | + AWS.config._region = this._region; |
| 29 | + this._s3Client = new AWS.S3(s3Options); |
| 30 | + } |
| 31 | + |
| 32 | + // For a given config object, filename, and data, store a file in S3 |
| 33 | + // Returns a promise containing the S3 object creation response |
| 34 | + createFileAsync(config, filename, data) { |
| 35 | + let params = { |
| 36 | + Key: this._bucketPrefix + filename, |
| 37 | + Body: data |
| 38 | + }; |
| 39 | + if (this._directAccess) { |
| 40 | + params.ACL = "public-read" |
| 41 | + } |
| 42 | + return new Promise((resolve, reject) => { |
| 43 | + this._s3Client.upload(params, (err, data) => { |
| 44 | + if (err !== null) { |
| 45 | + return reject(err); |
| 46 | + } |
| 47 | + resolve(data); |
| 48 | + }); |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + // Search for and return a file if found by filename |
| 53 | + // Returns a promise that succeeds with the buffer result from S3 |
| 54 | + getFileDataAsync(config, filename) { |
| 55 | + let params = {Key: this._bucketPrefix + filename}; |
| 56 | + return new Promise((resolve, reject) => { |
| 57 | + this._s3Client.getObject(params, (err, data) => { |
| 58 | + if (err !== null) { |
| 59 | + return reject(err); |
| 60 | + } |
| 61 | + resolve(data.Body); |
| 62 | + }); |
| 63 | + }); |
| 64 | + } |
| 65 | + |
| 66 | + // Generates and returns the location of a file stored in S3 for the given request and filename |
| 67 | + // The location is the direct S3 link if the option is set, otherwise we serve the file through parse-server |
| 68 | + getFileLocation(config, filename) { |
| 69 | + if (this._directAccess) { |
| 70 | + return ('https://' + this.bucket + '._s3Client.amazonaws.com' + '/' + this._bucketPrefix + filename); |
| 71 | + } |
| 72 | + return (config.mount + '/files/' + config.applicationId + '/' + encodeURIComponent(filename)); |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +export default S3Adapter; |
0 commit comments