-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandle-file.js
105 lines (93 loc) · 2.75 KB
/
handle-file.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
/**
* Class with functions to handle files
* @author Keller Kichel
* */
module.exports = class HandleFile {
/**
* Initialize the allowedEXT array with the allowed extensions
* @param {Object} req.query
*/
constructor({ ext, addext }) {
this.allowedEXT = ext ? ext.split(',') : ['jpg', 'bmp', 'png', 'gif', 'jpeg', 'svg', 'mp3'];
this.addExtension(addext);
}
/**
* Remove base folder from the passed folder path
* @example
* // return "media/noticias/diversas/imagem.jpg"
* handleFile.adjustPath('C:/Compartilhada/media/noticias/diversas/imagem.jpg', 'C:/Compartilhada');
*
* @param {String} folder
* @param {String} base
*
* @returns {String} Clean path
*/
adjustPath(folder, base) {
return folder.replace(/\\/g, '/').replace(base, '').replace(/^\//g, '');
}
/**
* Add extension to allowed extension list
* @param {String} ext - Can be comma separated strings
*/
addExtension(ext) {
if (!ext) return;
const extArr = ext.split(',');
extArr.forEach(item => {
if (!this.allowedEXT.includes(item))
this.allowedEXT.push(item);
});
}
/**
* Remove extension from allowed extension list
* @param {String} ext - Can be comma separated strings
*/
removeExtension(ext) {
if (!ext) return;
const extArr = ext.split(',');
extArr.forEach(item => {
if (!this.allowedEXT.includes(item))
this.allowedEXT.splice(this.allowedEXT.indexOf(item), 1);
});
}
/**
* Adjust path to return a JSON Object
* @param {String} paths
* @param {String} base
*
* @returns {Object} JSON Object
*/
dealPaths(paths, base) {
let info = {};
paths.map(path => {
const data = this.adjustPath(path, base).split('/');
let folder = info;
while (data.length) {
const fold = data.shift();
if (!folder.hasOwnProperty(fold))
folder[fold] = {};
folder = folder[fold];
}
});
return info;
}
/**
* Get only the files with allowed extension
* @param {Array} files
* @returns {Array} Allowed files
* @deprecated since version 1.1
*/
dealFiles(files) {
return files.filter(file => {
const info = file.split('.');
return this.checkExt(info[info.length]);
});
}
/**
* Validate extension with allowed extension array
* @param {String} extension
* @returns {Boolean}
*/
checkExt(ext) {
return this.allowedEXT.includes(ext.replace(/([^\w]*)/g,''));
}
}