All files / api-build/utils file-utils.js

97.06% Statements 33/34
83.33% Branches 10/12
100% Functions 9/9
97.06% Lines 33/34
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 711x 1x 1x 1x   1x 2x     2x     1x 4x 4x           1x 2x 2x 2x 7x   2x 2x           1x 3x 777679x 2x 2x         777677x         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');
 
exports.file = (p) => {
  Iif (exports.isUrl(p)) {
    return request.get({ url: p, encoding: null });
  }
  return fs.createReadStream(p);
};
 
exports.isUrl = (s) => {
  const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
  return regexp.test(s);
};
 
// Converts a stream to a buffer
// Useful for locally calling a service
// with a file
exports.streamToBuffer = (s) => {
  return new Promise((resolve) => {
    const out = [];
    s.on('data', (data) => {
      out.push(data);
    });
    s.on('end', () => {
      resolve(Buffer.concat(out));
    });
  });
};
 
// Converts buffers in response to file type
exports.parseFileResponse = (response) => {
  return JSON.parse(response, (k, v) => {
    if (v && v.type === 'Buffer') {
      const type = fileType(Buffer.from(v.data));
      return {
        type: type ? type.ext : 'string',
        file: Buffer.from(v.data),
      };
    }
    return v;
  });
};
 
// 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;
};