-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
index.js
207 lines (191 loc) · 6.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// S3Adapter
//
// Stores Parse files in AWS S3.
const AWS = require('aws-sdk');
const optionsFromArguments = require('./lib/optionsFromArguments');
const awsCredentialsDeprecationNotice = function awsCredentialsDeprecationNotice() {
// eslint-disable-next-line no-console
console.warn('Passing AWS credentials to this adapter is now DEPRECATED and will be removed in a future version',
'See: https://github.com/parse-server-modules/parse-server-s3-adapter#aws-credentials for details');
};
const serialize = (obj) => {
const str = [];
Object.keys(obj).forEach((key) => {
if (obj[key]) {
str.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`);
}
});
return str.join('&');
};
class S3Adapter {
// Creates an S3 session.
// Providing AWS access, secret keys and bucket are mandatory
// Region will use sane defaults if omitted
constructor(...args) {
const options = optionsFromArguments(args);
this._region = options.region;
this._bucket = options.bucket;
this._bucketPrefix = options.bucketPrefix;
this._directAccess = options.directAccess;
this._fileAcl = options.fileAcl;
this._baseUrl = options.baseUrl;
this._baseUrlDirect = options.baseUrlDirect;
this._signatureVersion = options.signatureVersion;
this._globalCacheControl = options.globalCacheControl;
this._encryption = options.ServerSideEncryption;
this._generateKey = options.generateKey;
// Optional FilesAdaptor method
this.validateFilename = options.validateFilename;
const s3Options = {
params: { Bucket: this._bucket },
region: this._region,
signatureVersion: this._signatureVersion,
globalCacheControl: this._globalCacheControl,
};
if (options.accessKey && options.secretKey) {
awsCredentialsDeprecationNotice();
s3Options.accessKeyId = options.accessKey;
s3Options.secretAccessKey = options.secretKey;
}
Object.assign(s3Options, options.s3overrides);
this._s3Client = new AWS.S3(s3Options);
this._hasBucket = false;
}
createBucket() {
let promise;
if (this._hasBucket) {
promise = Promise.resolve();
} else {
promise = new Promise((resolve) => {
this._s3Client.createBucket(() => {
this._hasBucket = true;
resolve();
});
});
}
return promise;
}
// For a given config object, filename, and data, store a file in S3
// Returns a promise containing the S3 object creation response
createFile(filename, data, contentType, options = {}) {
const params = {
Key: this._bucketPrefix + filename,
Body: data,
};
if (this._generateKey instanceof Function) {
params.Key = this._bucketPrefix + this._generateKey(filename);
}
if (this._fileAcl) {
if (this._fileAcl === 'none') {
delete params.ACL;
} else {
params.ACL = this._fileAcl;
}
} else if (this._directAccess) {
params.ACL = 'public-read';
}
if (contentType) {
params.ContentType = contentType;
}
if (this._globalCacheControl) {
params.CacheControl = this._globalCacheControl;
}
if (this._encryption === 'AES256' || this._encryption === 'aws:kms') {
params.ServerSideEncryption = this._encryption;
}
if (options.metadata && typeof options.metadata === 'object') {
params.Metadata = options.metadata;
}
if (options.tags && typeof options.tags === 'object') {
const serializedTags = serialize(options.tags);
params.Tagging = serializedTags;
}
return this.createBucket().then(() => new Promise((resolve, reject) => {
this._s3Client.upload(params, (err, response) => {
if (err !== null) {
return reject(err);
}
return resolve(response);
});
}));
}
deleteFile(filename) {
return this.createBucket().then(() => new Promise((resolve, reject) => {
const params = {
Key: this._bucketPrefix + filename,
};
this._s3Client.deleteObject(params, (err, data) => {
if (err !== null) {
return reject(err);
}
return resolve(data);
});
}));
}
// Search for and return a file if found by filename
// Returns a promise that succeeds with the buffer result from S3
getFileData(filename) {
const params = { Key: this._bucketPrefix + filename };
return this.createBucket().then(() => new Promise((resolve, reject) => {
this._s3Client.getObject(params, (err, data) => {
if (err !== null) {
return reject(err);
}
// Something happened here...
if (data && !data.Body) {
return reject(data);
}
return resolve(data.Body);
});
}));
}
// Generates and returns the location of a file stored in S3 for the given request and filename
// The location is the direct S3 link if the option is set,
// otherwise we serve the file through parse-server
getFileLocation(config, filename) {
const fileName = filename.split('/').map(encodeURIComponent).join('/');
if (this._directAccess) {
if (this._baseUrl) {
if (typeof this._baseUrl === 'function') {
if (this._baseUrlDirect) {
return `${this._baseUrl(config, filename)}/${fileName}`;
}
return `${this._baseUrl(config, filename)}/${this._bucketPrefix + fileName}`;
}
if (this._baseUrlDirect) {
return `${this._baseUrl}/${fileName}`;
}
return `${this._baseUrl}/${this._bucketPrefix + fileName}`;
}
return `https://${this._bucket}.s3.amazonaws.com/${this._bucketPrefix + fileName}`;
}
return (`${config.mount}/files/${config.applicationId}/${fileName}`);
}
handleFileStream(filename, req, res) {
const params = {
Key: this._bucketPrefix + filename,
Range: req.get('Range'),
};
return this.createBucket().then(() => new Promise((resolve, reject) => {
this._s3Client.getObject(params, (error, data) => {
if (error !== null) {
return reject(error);
}
if (data && !data.Body) {
return reject(data);
}
res.writeHead(206, {
'Accept-Ranges': data.AcceptRanges,
'Content-Length': data.ContentLength,
'Content-Range': data.ContentRange,
'Content-Type': data.ContentType,
});
res.write(data.Body);
res.end();
return resolve(data.Body);
});
}));
}
}
module.exports = S3Adapter;
module.exports.default = S3Adapter;