Parcourir la source

Merge pull request #1436 from allenfantasy/feature/restriction-fail

feat: fire event when restriction-failed
Artur Paikin il y a 6 ans
Parent
commit
56426ccff2

+ 1 - 0
packages/@uppy/core/src/index.js

@@ -454,6 +454,7 @@ class Uppy {
     try {
       this._checkRestrictions(newFile)
     } catch (err) {
+      this.emit('restriction-failed', newFile, err)
       onError(err)
     }
 

+ 24 - 0
packages/@uppy/core/src/index.test.js

@@ -1,5 +1,6 @@
 const fs = require('fs')
 const path = require('path')
+const prettyBytes = require('prettier-bytes')
 const Core = require('./index')
 const Plugin = require('./Plugin')
 const AcquirerPlugin1 = require('../../../../test/mocks/acquirerPlugin1')
@@ -1270,6 +1271,29 @@ describe('src/Core', () => {
         expect(core.getState().info.message).toEqual('This file exceeds maximum allowed size of 1.2 KB')
       }
     })
+
+    it('should emit `restriction-failed` event when some rule is violated', () => {
+      const maxFileSize = 100
+      const core = new Core({
+        restrictions: {
+          maxFileSize
+        }
+      })
+      const restrictionsViolatedEventMock = jest.fn()
+      const file = {
+        name: 'test.jpg',
+        data: new Blob([Buffer.alloc(2 * maxFileSize)])
+      }
+      const errorMessage = `${core.i18n('exceedsSize')} ${prettyBytes(maxFileSize)}`
+      try {
+        core.on('restriction-failed', restrictionsViolatedEventMock)
+        core.addFile(file)
+      } catch (err) {}
+
+      expect(restrictionsViolatedEventMock.mock.calls.length).toEqual(1)
+      expect(restrictionsViolatedEventMock.mock.calls[0][0].name).toEqual(file.name)
+      expect(restrictionsViolatedEventMock.mock.calls[0][1].message).toEqual(errorMessage)
+    })
   })
 
   describe('actions', () => {

+ 10 - 0
website/src/docs/uppy.md

@@ -642,3 +642,13 @@ Fired when “info” message should be hidden in the UI. See [`info-visible`](#
 ### `cancel-all`
 
 Fired when [`uppy.cancelAll()`]() is called, all uploads are canceled, files removed and progress is reset.
+
+### `restriction-failed`
+
+Fired when a file violates certain restrictions when added. This event is just providing another choice for those who want to customize the behavior of file upload restrictions.
+
+```javascript
+uppy.on('restriction-failed', (file, error) => {
+  // do some customized logic like showing system notice to users
+})
+```