All files / utils downloadBlob.js

6.66% Statements 1/15
0% Branches 0/12
0% Functions 0/2
6.66% Lines 1/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                30x                                                                    
/*
 * The options block allows for a very customisable approach to naming files
 * and applying extensions. The default options are chosen in order to keep default
 * behaviour found in other apps, but this can now be changed use case by use case.
 *
 * This is copied from stripes-erm-components
 */
 
const downloadBlob = (
  name,
  {
    fileExt = '',
    spaceDelimiter = '_',
    dotDelimiter = '',
    processWhitespace = true,
    processDots = false
  } = {}
) => {
  let downloadName = name;
  if (processWhitespace) {
    downloadName = downloadName.replaceAll(/\s/g, spaceDelimiter);
  }
 
  if (processDots) {
    downloadName = downloadName.replaceAll(/\./g, dotDelimiter);
  }
 
  if (fileExt.length) {
    downloadName = `${downloadName}.${fileExt}`;
  }
 
  return blob => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = downloadName;
    a.click();
    URL.revokeObjectURL(url);
  };
};
 
export default downloadBlob;