file-appender.js 1.6 KB

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