All files / api ApiMethod.js

100% Statements 12/12
78.57% Branches 11/14
100% Functions 2/2
100% Lines 12/12
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              7x                     9x   9x         9x           9x             9x 8x     9x 9x 8x 2x       7x      
/* @flow */
 
import url from "url";
import invariant from "invariant";
import { isApiMethod, isAuthMethod } from "../utils";
import ApiRequest from "./ApiRequest";
import type { ApiResult, ApiMethodOptions } from "./types";
const defaultApiServer = "api.pcloud.com";
 
export default function ApiMethod(
  method: string,
  options: ApiMethodOptions = {}
): Promise<ApiResult> {
  const {
    apiServer = defaultApiServer,
    apiProtocol = "https",
    params = {},
    ...requestParams
  } = options;
 
  invariant(
    isApiMethod(method),
    "Method `" + method + "` is not pCloud API method."
  );
 
  invariant(
    !isAuthMethod(method) || "auth" in params || "access_token" in params ||
      "username" in params,
    "`auth` must be present for methods that require authentication."
  );
 
  const requestUrl: string = url.format({
    protocol: apiProtocol,
    host: apiServer,
    pathname: method,
    query: params
  });
 
  if (requestParams.responseType === undefined) {
    requestParams.responseType = "json";
  }
 
  return ApiRequest(requestUrl, requestParams).then((response: ApiResult) => {
    if (requestParams.responseType === "json") {
      if (response.result !== 0) {
        return Promise.reject(response);
      }
    }
 
    return response;
  });
}