UNPKG

1.6 kBJavaScriptView Raw
1var objectAssign = require('object-assign')
2
3function arrayRemove (arr, item) {
4 var idx = arr.indexOf(item)
5 if (~idx) arr.splice(idx, 1)
6}
7
8function FileAppender (strategy, req) {
9 this.strategy = strategy
10 this.req = req
11
12 switch (strategy) {
13 case 'VALUE': break
14 case 'ARRAY': req.files = []; break
15 case 'OBJECT': req.files = Object.create(null); break
16 default: throw new Error('Unknown file strategy: ' + strategy)
17 }
18}
19
20FileAppender.prototype.insertPlaceholder = function (file) {
21 var placeholder = {
22 fieldname: file.fieldname
23 }
24
25 switch (this.strategy) {
26 case 'VALUE': break
27 case 'ARRAY': this.req.files.push(placeholder); break
28 case 'OBJECT':
29 if (this.req.files[file.fieldname]) {
30 this.req.files[file.fieldname].push(placeholder)
31 } else {
32 this.req.files[file.fieldname] = [placeholder]
33 }
34 break
35 }
36
37 return placeholder
38}
39
40FileAppender.prototype.removePlaceholder = function (placeholder) {
41 switch (this.strategy) {
42 case 'VALUE': break
43 case 'ARRAY': arrayRemove(this.req.files, placeholder); break
44 case 'OBJECT':
45 if (this.req.files[placeholder.fieldname].length === 1) {
46 delete this.req.files[placeholder.fieldname]
47 } else {
48 arrayRemove(this.req.files[placeholder.fieldname], placeholder)
49 }
50 break
51 }
52}
53
54FileAppender.prototype.replacePlaceholder = function (placeholder, file) {
55 if (this.strategy === 'VALUE') {
56 this.req.file = file
57 return
58 }
59
60 delete placeholder.fieldname
61 objectAssign(placeholder, file)
62}
63
64module.exports = FileAppender