generateFileID.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. function encodeCharacter(character) {
  3. return character.charCodeAt(0).toString(32);
  4. }
  5. function encodeFilename(name) {
  6. let suffix = '';
  7. return name.replace(/[^A-Z0-9]/ig, character => {
  8. suffix += `-${encodeCharacter(character)}`;
  9. return '/';
  10. }) + suffix;
  11. }
  12. /**
  13. * Takes a file object and turns it into fileID, by converting file.name to lowercase,
  14. * removing extra characters and adding type, size and lastModified
  15. *
  16. * @param {object} file
  17. * @returns {string} the fileID
  18. */
  19. function generateFileID(file) {
  20. // It's tempting to do `[items].filter(Boolean).join('-')` here, but that
  21. // is slower! simple string concatenation is fast
  22. let id = 'uppy';
  23. if (typeof file.name === 'string') {
  24. id += `-${encodeFilename(file.name.toLowerCase())}`;
  25. }
  26. if (file.type !== undefined) {
  27. id += `-${file.type}`;
  28. }
  29. if (file.meta && typeof file.meta.relativePath === 'string') {
  30. id += `-${encodeFilename(file.meta.relativePath.toLowerCase())}`;
  31. }
  32. if (file.data.size !== undefined) {
  33. id += `-${file.data.size}`;
  34. }
  35. if (file.data.lastModified !== undefined) {
  36. id += `-${file.data.lastModified}`;
  37. }
  38. return id;
  39. }
  40. module.exports = generateFileID;