All files / src/utils file-utils.js

92.68% Statements 38/41
83.33% Branches 10/12
90% Functions 9/10
92.68% Lines 38/41
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 831x 1x 1x 1x 1x   1x             1x 2x 2x 1x   1x             1x 2x 2x 2x 7x   2x 2x   2x           1x 3x 777679x 2x 2x         777677x       1x 4x 4x       1x 4x 4x 5x   1x     1x       4x 2x         2x     4x    
const fileType = require('file-type');
const Stream = require('stream');
const request = require('request-promise');
const fs = require('fs');
const { URL } = require('url');
 
exports.file = (p) => {
  if (exports.isUrl(p)) {
    return request.get({ url: p, encoding: null });
  }
  return fs.createReadStream(p);
};
 
exports.isUrl = (s) => {
  try {
    new URL(s); // eslint-disable-line no-new
    return true;
  } catch (e) {
    return false;
  }
};
 
// Converts a stream to a buffer
// Useful for locally calling a service
// with a file
exports.streamToBuffer = (s) => {
  return new Promise((resolve, reject) => {
    const out = [];
    s.on('data', (data) => {
      out.push(data);
    });
    s.on('end', () => {
      resolve(Buffer.concat(out));
    });
    s.on('error', reject);
  });
};
 
// Converts buffers in response to file type
// Only used for api.local
exports.parseLocalFileResponse = (response) => {
  return JSON.parse(response, (k, v) => {
    if (v && v.type === 'Buffer') {
      const file = Buffer.from(v.data);
      return {
        type: exports.getBufferType(file),
        file,
      };
    }
    return v;
  });
};
 
exports.getBufferType = (buffer) => {
  const type = fileType(buffer);
  return type ? type.ext : 'string';
};
 
// Converts data into the file type if stream or buffer
exports.convertToFileType = async (data) => {
  const out = {};
  for (const d in data) {
    if (data[d] instanceof Stream) {
      /* eslint-disable no-await-in-loop */
      const file = await exports.streamToBuffer(data[d]);
      /* eslint-enable no-await-in-loop */
 
      out[d] = {
        file: JSON.parse(JSON.stringify(file)),
        type: fileType(file).ext,
      };
    } else if (Buffer.isBuffer(data[d])) {
      out[d] = {
        file: JSON.parse(JSON.stringify(data[d])),
        type: fileType(data[d]).ext,
      };
    } else {
      out[d] = data[d];
    }
  }
  return out;
};