All files / client/methods download.js

10% Statements 1/10
0% Branches 0/6
12.5% Functions 1/8
11.11% Lines 1/9
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                19x                                              
/* @flow */
 
import ApiRequest from "../../api/ApiRequest";
import type { DownloadOptions } from "../../api/types";
import type { FileLocal } from "../types";
import fs from "fs";
import path from "path";
 
export default () => (filename: string, options: DownloadOptions = {}) => (url: string): Promise<FileLocal> => {
  const { onBegin = () => {}, onProgress = () => {}, onFinish = () => {} } = options;
 
  onBegin();
  return ApiRequest(url, {
    type: "arraybuffer",
    pipe: fs.createWriteStream(filename),
    onProgress: progress => {
      if (progress.direction === "download") {
        onProgress(progress);
      }
    }
  }).then(() => {
    const file: FileLocal = {
      path: filename,
      name: path.basename(filename),
      size: fs.statSync(filename).size
    };
 
    onFinish(file);
    return file;
  });
};