Source: custom-code/custom-code.js

/**
 * Copyright© 2016, Oracle and/or its affiliates. All rights reserved.
 * Created by ddrobins on 7/28/15.
 */


/**
 * This class provides a way to invoke custom API endpoints for the
 * currently active mobile backend. Callers should use
 * MobileBackend's [CustomCode()]{@link MobileBackend#CustomCode} property.
 * @constructor
 * @private
 * @global
 */
function CustomCode(backend, utils, platform) {
    /**
     * Callback invoked after successfully flushing analytics events.
     * @callback CustomCode~successCallback
     * @deprecated Use promises instead
     */

    /**
     * Callback invoked on error.
     * @callback CustomCode~errorCallback
     * @param statusCode {Number} Any HTTP status code returned from the server, if available.
     * @param message {String} The HTTP payload from the server, if available, or an error message.
     * @deprecated Use promises instead
     */

  /**
   * @ignore
   * @type {{GET: string, POST: string, PUT: string, DELETE: string, PATCH: string}}
   */
  var httpMethods = {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE', PATCH: 'PATCH'};

  var _backend = backend;

  function checkParameters(params, comparison) {
    return isJSON(params) && params && params != undefined && typeof params == comparison;
  }

  function isJSON(params) {
    if (typeof params != 'string')
      params = JSON.stringify(params);

    try {
      JSON.parse(params);
      return true;
    } catch (e) {
      return false;
    }
  }


    /**
     * Allows the user to call custom Code defined on the UI and assigned to the backend defined by the user
     * This custom endpoint should return data only in JSON format.
     * @param path {String} The path of the endpoint following the platform prefix, i.e. {BaseUrl}/mobile/custom/{path to the custom API endpoint}.
     * @param method {String} HTTP method that is invoked.
     * @param data {Object} Data that is inserted into the call on the server for POST and PUT methods. Only accepts a JSON object and/or JavaScript array.
     * @param [successCallback] {CustomCode~successCallback} Optional callback invoked on success that returns the status code and the data from the request (deprecated use promises instead).
     * @param [errorCallback] {CustomCode~errorCallback} Optional callback invoked on failure that returns the status code and the data from the request (deprecated use promises instead).
     * @return {Promise.<NetworkResponse|NetworkResponse>}
     * @example path: "TasksAPI/tasks/100"
     * @example method: "GET,POST,PUT,DELETE"
     * @example data:  {
        "name": "Complete reports",
        "completed": false,
        "priority": "high",
        "dueDate": "2015-03-15T17:00:00Z"
      }
     * These methods must be defined in the custom API for these methods to work.
     * @example <caption>Example usage of mcs.MobileBackend.invokeCustomCodeJSONRequest()</caption>
     mcs.MobileBackend.customCode
     .invokeCustomCodeJSONRequest('TaskApi1/tasks/100' ,'GET' ,null)
     .then(invokeSuccess, invokeError);

   function invokeSuccess(response) {
      console.log(response.data);// returns object in JSON format
    }

   function invokeError(response) {

    }
   //output
   {
      "name": "Complete reports",
      "completed": false,
      "priority": "high",
      "dueDate": "2015-03-15T17:00:00Z"
    }
   */
  this.invokeCustomCodeJSONRequest = function (path, method, data, successCallback, errorCallback) {
    if (method in httpMethods) {

      if(method === httpMethods.DELETE && data){
        if (errorCallback != null) {
          errorCallback(500, 'DELETE method content body');
          return undefined;
        } else {
          return Promise.reject(new NetworkResponse(500, 'DELETE method content body'));
        }
      }

      var headers = _backend.getHttpHeaders(utils.MODULE_NAMES.CUSTOM_CODE);
      headers[utils.HEADERS.CONTENT_TYPE] = 'application/json';

      var customData = data ? JSON.stringify(data) : null;

      return platform.invokeService({
        method: method,
        url: _backend.getCustomCodeUrl(path),
        headers: headers,
        data: customData
      }).then(invokeServiceSuccess, invokeServiceError);
    } else {
      if (errorCallback != null) {
        errorCallback(501, 'Method Not Implemented');
        return undefined;
      } else {
        return Promise.reject(new NetworkResponse(501, 'Method Not Implemented'));
      }
    }

    function invokeServiceSuccess(response) {
      if (successCallback) {
        successCallback(response.statusCode, response.data, response.headers);
      }
      return response;
    }

    function invokeServiceError(response) {
      if (errorCallback) {
        errorCallback(response.statusCode, response.data);
      } else {
        return Promise.reject(response);
      }
    }
  };
}