createUppy.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const Uppy = require('@uppy/core')
  2. const has = require('@uppy/utils/lib/hasProperty')
  3. const eventNames = {
  4. // File management events
  5. onFileAdded: 'file-added',
  6. onFileRemoved: 'file-removed',
  7. // Transloadit events
  8. onImportError: 'transloadit:import-error',
  9. onAssemblyCreated: 'transloadit:assembly-created',
  10. onAssemblyExecuting: 'transloadit:assembly-executing',
  11. onAssemblyError: 'transloadit:assembly-error',
  12. onAssemblyComplete: 'transloadit:complete',
  13. onResult: 'transloadit:result',
  14. // Upload events
  15. onStart: 'upload',
  16. onPause: 'pause-all',
  17. onFilePause: 'upload-pause',
  18. onCancel: 'cancel-all',
  19. onError: 'error', // mostly akin to promise rejection
  20. onFileCancel: 'upload-cancel',
  21. onFileProgress: 'upload-progress',
  22. onFileError: 'upload-error',
  23. onUploaded: 'transloadit:upload',
  24. onComplete: 'complete' // mostly akin to promise resolution
  25. }
  26. const uppyOptionNames = [
  27. 'autoProceed',
  28. 'restrictions',
  29. 'meta',
  30. 'onBeforeFileAdded',
  31. 'onBeforeUpload',
  32. 'debug'
  33. ]
  34. function createUppy (opts, overrides = {}) {
  35. const uppyOptions = {}
  36. uppyOptionNames.forEach((name) => {
  37. if (has(opts, name)) uppyOptions[name] = opts[name]
  38. })
  39. Object.assign(uppyOptions, overrides)
  40. const uppy = Uppy(uppyOptions)
  41. // Builtin event aliases
  42. Object.keys(eventNames).forEach((optionName) => {
  43. const eventName = eventNames[optionName]
  44. if (typeof opts[optionName] === 'function') {
  45. uppy.on(eventName, opts[optionName])
  46. }
  47. })
  48. // Custom events (these should probably be added to core)
  49. if (typeof opts.onProgress === 'function') {
  50. uppy.on('upload-progress', () => {
  51. const { totalProgress } = uppy.getState()
  52. opts.onProgress.call(uppy, totalProgress)
  53. })
  54. }
  55. return uppy
  56. }
  57. module.exports = createUppy