file-appender.js 1.6 KB

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