All files / src/modules uploadPackage.js

100% Statements 13/13
100% Branches 11/11
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                    5x 1x   4x 1x   3x 1x     2x   2x     12x           2x   2x 1x     2x            
/**
 * Upload a package.
 * @module src/modules/uploadPackage
 * @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 upload, must be a File object (browser). Buffer or ./path/to/file (NodeJS).
 * @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.upload(url, request, options);
}
 
const privateMethods = {
  /**
   * Upload package from a NodeJS environment.
   * @private
   */
  upload(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);
  }
}