-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
223 lines (190 loc) · 6.57 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
'use strict';;
//const AWS = require('aws-sdk');
const { Upload } = require('@aws-sdk/lib-storage');
const { DeleteObjectCommand, S3Client } = require('@aws-sdk/client-s3');
const mime = require('mime-types');
const _ = require('underscore');
const uuid = require('uuid');
const path = require('path');
const fs = require('fs');
const fsExt = require('fs-extra');
class ValidationError extends Error {
constructor(message, type) {
super(message);
// assign the error class name in your custom error (as a shortcut)
this.name = this.constructor.name;
this.type = type;
this.statusCode = 403;
// capturing the stack trace keeps the reference to your error class
Error.captureStackTrace(this, this.constructor);
}
}
/**
*
* @param {object} options settings for upload
* @returns {object} Instance of StreamUpload
*/
function StreamUpload(options) {
const that = this;
that.settings = {
allowedExt: [],
allowedTypes: [],
baseFolder: '',
storage: {}
};
that.size = 0;
const __parseExtensions = function () {
that.settings.allowedExt.forEach(function (ext) {
const fileType = mime.lookup(ext);
if (fileType) {
that.settings.allowedTypes.push(fileType);
}
});
_.uniq(that.settings.allowedTypes);
};
const __setExtensions = function (extensions) {
if (!Array.isArray(extensions)) {
extensions = [extensions];
}
if (extensions.length) {
that.settings.allowedExt = extensions;
__parseExtensions();
}
return that.settings.allowedExt;
};
const __setTypes = function (types) {
if (!Array.isArray(types)) {
types = [types];
}
if (types.length) {
that.settings.allowedTypes = that.settings.allowedTypes.concat(types);
_.uniq(that.settings.allowedTypes);
}
return that.settings.allowedTypes;
};
const __setBaseFolder = function (folder) {
if (_.isString(folder)) {
that.settings.baseFolder = path.normalize(folder);
}
return that.settings.baseFolder;
};
const __setStorage = function (params) {
if (_.isObject(params)) {
that.settings.storage = params;
}
return that.settings.storage;
};
const __init = function (options) {
if (options.extensions) {
__setExtensions(options.extensions);
}
if (options.types) {
__setTypes(options.types);
}
__setBaseFolder(options.baseFolder);
__setStorage(options.storage);
};
if (options) {
__init(options);
}
const __checkFileType = function (type, name) {
const fileType = mime.lookup(path.extname(name));
if (fileType !== type) {
return false;
} else if (that.settings.allowedTypes && that.settings.allowedTypes.length) {
for (let i = 0; i < that.settings.allowedTypes.length; i++) {
const exp = new RegExp(that.settings.allowedTypes[i].replace('+', '\\+').replace('.', '\\.'));
if (exp.test(type)) {
return true;
}
}
return false;
} else {
return true;
}
};
const __uploadToS3 = async function (inputStream) {
const config = {
credentials: {
accessKeyId: that.settings.storage.accessKeyId,
secretAccessKey: that.settings.storage.secretAccessKey
},
region: that.settings.storage.region
};
// AWS.config.update(config);
// AWS.config.update(config);
const params = { Key: that.filename, Bucket: that.settings.storage.bucket, Body: inputStream, ACL: 'public-read' };
const s3Client = new S3Client(config);
const upload = new Upload({
client: s3Client,
params
});
const data = await upload.done();
return {
size: that.size,
filename: data.Location
};
};
const __uploadToLocal = function (inputStream) {
return new Promise((resolve, reject) => {
// Make sure the output directory is there.
fsExt.ensureDirSync(path.dirname(that.filename));
const wr = fs.createWriteStream(that.filename);
inputStream
.pipe(wr)
.on('error', reject)
.on('finish', function () {
return resolve({
size: that.size,
filename: that.filename
});
});
});
};
const __deletePartials = function () {
if (that.settings.storage.type && that.settings.storage.type.toLowerCase() === 's3') {
const config = {
credentials: {
accessKeyId: that.settings.storage.accessKeyId,
secretAccessKey: that.settings.storage.secretAccessKey
},
region: that.settings.storage.region
};
const s3Client = new S3Client(config);
const deleteCommand = new DeleteObjectCommand({ Key: that.filename, Bucket: that.settings.storage.bucket });
s3Client
.send(deleteCommand);
} else if (fs.existsSync(that.filename)) {
fs.promises.unlink(that.filename);
}
};
const __upload = async function (stream, params) {
that.filename = params.filename || path.join(that.settings.baseFolder, uuid.v4());
const isValid = __checkFileType(params.type, params.filename);
if (isValid) {
try {
if (that.settings.storage.type && that.settings.storage.type.toLowerCase() === 's3') {
return await __uploadToS3(stream);
} else {
return __uploadToLocal(stream);
}
} catch (err) {
console.log('ERROR', err);
stream.emit('error', err);
}
} else {
stream.emit('error', new ValidationError('File type ' + params.type + ' is invalid', 'fileType'));
}
};
return {
upload: __upload,
settings: that.settings,
init: __init,
setExtensions: __setExtensions,
setTypes: __setTypes,
setStorage: __setStorage,
checkFileType: __checkFileType,
deletePartials: __deletePartials
};
}
module.exports = StreamUpload;