All files / src/modules uploadPackageFromBrowser.js

100% Statements 13/13
100% Branches 11/11
100% Functions 1/1
100% Lines 13/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 38 39 40 41 42 43                    5x 1x   4x 1x   3x 1x     2x   2x     13x           2x   2x 1x     2x          
/**
 * Upload a package.
 * @module src/modules/uploadPackageFromBrowser
 * @param {Object} options - Repository options.
 * @param {string} options.repo - The fully-qualified repository name, i.e., 'username/reponame'.
 * @param {string} options.file - The file to be uploaded, must be a File object.
 * @param {string} options.filename - The filename of the package.
 * @return {Promise} The superagent promise object.
 */
export default (request, options) => {
  if(!options || !options.repo || options.repo.split("/").length < 2) {
    throw new Error("Repository path must be in the fully-qualified format - user/repo");
  }
  if(!options.file) {
    throw new Error("Expects an object with string file path (node) or File (browser) as a value");
  }
  if(!options.filename) {
    throw new Error("Expects a filename");
  }
 
  let url = [options.baseUrl + "repos", options.repo, "packages.json"].join("/");
 
  return privateMethods.browserUpload(url, request, options);
}
 
const privateMethods = {
  /**
   * Upload package from a browser environment.
   * @private
   */
  browserUpload(url, request, options) {
    let fields = {filename: options.filename};
 
    if(options.dist) {
      fields["package[distro_version_id]"] = options.dist;
    }
 
    return request.post(url)
      .field(fields)
      .attach("package[package_file]", options.file);
  }
}