All files / api ApiRequest.js

80% Statements 36/45
76.47% Branches 26/34
66.67% Functions 8/12
80% Lines 36/45
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150              18x     18x     13x                 13x   13x 1x 1x     1x 1x               12x       12x     12x         12x 2x   2x 2x   2x       12x 1x     12x   12x             12x                   12x                                           12x   10x 9x   9x 9x 1x 1x                         9x 9x           9x   9x                   18x   2x    
/* @flow */
 
import request from "superagent";
import invariant from "invariant";
import { httpProgressMiddleware } from "../utils";
import type { ApiRequestOptions, ApiResult } from "./types";
 
let inProgress: { [id: string]: number } = {};
let waitCallbacks: {
  [id: string]: Array<[(T: ApiResult) => void, ApiRequestOptions]>
} = {};
 
export default function ApiRequest(url: string, options: ApiRequestOptions = {}): Promise<ApiResult> {
  invariant(url.length, "`url` is required.");
 
  let {
    method = "get",
    responseType = "json",
    onProgress = () => {},
    xhr = () => {},
    pipe = false,
    files = []
  } = options;
 
  if (method === "get" && url in inProgress) {
    Eif (waitCallbacks[url] === undefined) {
      waitCallbacks[url] = [];
    }
 
    return new Promise(resolve => {
      waitCallbacks[url].push([
        (response: ApiResult) => {
          resolve(response);
        },
        options
      ]);
    });
  } else {
    inProgress[url] = 1;
  }
 
  // call
  let req = request[method](url);
 
  // progress upload/download
  req.on("progress", onProgress);
 
  // attaching files
  // works for both node/web
  // in one case its path to file, in the other is File object
  if (files.length) {
    invariant(["put", "post"].indexOf(method) !== -1, "When uploading, `method` must be either `post` or `put`.");
 
    files.forEach(({ name = undefined, file }) => {
      invariant(file, "`file` is a required property of `files`.");
 
      req.attach(filenameKey(), file, name);
    });
  }
 
  if ("responseType" in req && responseType !== "json") {
    req.responseType(responseType);
  }
 
  Eif (ENV === "node") {
    // node only progress based on the stream events
    req.use(httpProgressMiddleware);
 
    /**
     * `superagent` cannot be used as then-able object when piping and since
     * when piping the "end" is called anyway, we need to create and
     * manage different promise for this case only.
     */
    Iif (pipe) {
      return new Promise((resolve, reject) => {
        req.pipe(pipe).on("finish", resolve).on("error", reject);
      });
    }
  }
 
  // pass xhr object before calling the request
  // important for custom checking the progress of the call
  // in case of intentionally blocking operations and so on...
  xhr(req.xhr);
 
  /*
  return new Promise((resolve, reject) => {
    req.end((error, response) => {
      if (error) {
        clearInProgressCallbacks();
        reject({ result: error.status || 500, error: "Network Error" });
      } else {
        if (responseType === "json") {
          const { body } = response;
 
          callbacksReceiveBody(body);
          resolve(body);
        } else if (responseType === "text") {
          resolve(response.text);
        }
      }
    });
  });
  */
 
  return req
    .then(response => {
      if (responseType === "json") {
        const { body } = response;
 
        callbacksReceiveBody(body);
        return body;
      } else Eif (responseType === "text") {
        return response.text;
      }
    })
    .catch(error => {
      const errorObj = { result: error.status || 500, error: "Network Error" };
 
      clearInProgressCallbacks();
 
      return Promise.reject(errorObj);
    });
 
  // clear currently running urls
  function clearInProgressCallbacks() {
    Eif (url in inProgress) {
      delete inProgress[url];
    }
  }
 
  // send all currently waiting tasks their data
  function callbacksReceiveBody(body) {
    clearInProgressCallbacks();
 
    Iif (url in waitCallbacks) {
      while (waitCallbacks[url].length) {
        const [callback] = waitCallbacks[url].shift();
 
        callback(body);
      }
    }
  }
}
 
let n = 1;
function filenameKey(): string {
  return "file-upload-" + ++n;
}