All files / client/methods upload.js

84.62% Statements 11/13
57.14% Branches 4/7
75% Functions 6/8
84.62% Lines 11/13
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            19x 1x 1x 1x   1x   1x 1x                       1x   1x 1x         1x    
/* @flow */
 
import invariant from "invariant";
import type { UploadOptions } from "../../api/types";
import type { MethodApi } from "../types";
 
export default ({ client }: MethodApi) => (file: string, folderid: number = 0, options: UploadOptions = {}) => {
  invariant(file, "`file` is required.");
  invariant(typeof file === "string", "`file` must be supplied");
  invariant(require("fs").existsSync(file), `File: ${file} is not accessible.`);
 
  const { onBegin = () => {}, onProgress = () => {}, onFinish = () => {} } = options;
 
  onBegin();
  return client
    .api("uploadfile", {
      method: "post",
      params: { folderid: folderid, nopartial: 1 },
      files: [{ file: file }],
      onProgress: progress => {
        if (progress.direction === "upload") {
          onProgress(progress);
        }
      }
    })
    .then(response => {
      const ret = apiResponseToReturn(response);
 
      onFinish(ret);
      return ret;
    });
};
 
function apiResponseToReturn({ metadata, checksums }) {
  return { metadata: metadata[0], checksums: checksums[0] };
}