Browse Source

Merge pull request #330 from transloadit/fix/fileID

Better `generateFileID`
Artur Paikin 7 years ago
parent
commit
016557e246
3 changed files with 20 additions and 12 deletions
  1. 3 2
      src/core/Core.test.js
  2. 12 7
      src/core/Utils.js
  3. 5 3
      src/core/Utils.test.js

+ 3 - 2
src/core/Core.test.js

@@ -385,8 +385,9 @@ describe('src/Core', () => {
         .then(() => core.upload())
         .then(() => {
           expect(postprocessor1.mock.calls.length).toEqual(1)
-          const lastModifiedTime = new Date()
-          const fileId = 'foojpg' + lastModifiedTime.getTime()
+          // const lastModifiedTime = new Date()
+          // const fileId = 'foojpg' + lastModifiedTime.getTime()
+          const fileId = 'uppy-foojpg-image'
 
           expect(postprocessor1.mock.calls[0][0].length).toEqual(1)
           expect(postprocessor1.mock.calls[0][0][0].substring(0, 17)).toEqual(

+ 12 - 7
src/core/Utils.js

@@ -107,17 +107,22 @@ function toArray (list) {
 }
 
 /**
- * Takes a fileName and turns it into fileID, by converting to lowercase,
- * removing extra characters and adding unix timestamp
+ * Takes a file object and turns it into fileID, by converting file.name to lowercase,
+ * removing extra characters and adding type, size and lastModified
  *
- * @param {String} fileName
+ * @param {Object} file
+ * @return {String} the fileID
  *
  */
 function generateFileID (file) {
-  let fileID = file.name.toLowerCase()
-  fileID = fileID.replace(/[^A-Z0-9]/ig, '')
-  fileID = fileID + file.data.lastModified
-  return fileID
+  // filter is needed to not join empty values with `-`
+  return [
+    'uppy',
+    file.name ? file.name.toLowerCase().replace(/[^A-Z0-9]/ig, '') : '',
+    file.type,
+    file.data.size,
+    file.data.lastModified
+  ].filter(val => val).join('-')
 }
 
 function extend (...objs) {

+ 5 - 3
src/core/Utils.test.js

@@ -5,16 +5,18 @@ const sampleImageDataURI =
 
 describe('core/utils', () => {
   describe('generateFileID', () => {
-    it('should take the filename object and produce a lowercase file id made up of the name and lastModified date', () => {
+    it('should take the filename object and produce a lowercase file id made up of uppy- prefix, file name (cleaned up to be lowercase, letters and numbers only), type, size and lastModified date', () => {
       const fileObj = {
         name: 'fOo0Fi@£$.jpg',
+        type: 'image/jpeg',
         data: {
-          lastModified: '2017-08-31T00:00:00.000Z'
+          lastModified: 1498510508000,
+          size: 2271173
         }
       }
 
       expect(utils.generateFileID(fileObj)).toEqual(
-        'foo0fijpg2017-08-31T00:00:00.000Z'
+        'uppy-foo0fijpg-image/jpeg-2271173-1498510508000'
       )
     })
   })