client/index.js

'use strict';

var BraintreeError = require('../lib/error');
var Client = require('./client');
var getConfiguration = require('./get-configuration').getConfiguration;
var packageVersion = require('package.version');

/** @module braintree/client */

/**
 * @function
 * @description This function is the entry point for the <code>braintree.client</code> module. It is used for creating {@link Client} instances that service communication to Braintree servers.
 * @param {object} options Object containing all {@link Client} options
 * @param {string} options.authorization A tokenizationKey or clientToken
 * @param {errback} callback The second argument, <code>data</code>, is the {@link Client} instance
 * @returns {void}
 * @example
 * var createClient = require('braintree-web/client').create;
 *
 * createClient({
 *   authorization: CLIENT_TOKEN
 * }, function (err, client) {
 *   ...
 * });
 * @static
 */
function create(options, callback) {
  if (!options.authorization) {
    callback(new BraintreeError({
      type: BraintreeError.types.MERCHANT,
      message: 'options.authorization is required'
    }));
    return;
  }

  getConfiguration(options, function (err, configuration) {
    var client;

    if (err != null) {
      // TODO: We will refactor this when braintree-request has better error handling.
      if (err.errors === 'Unknown error') {
        callback(new BraintreeError({
          type: BraintreeError.types.NETWORK,
          message: 'Cannot contact the gateway at this time.'
        }));
      } else {
        // TODO: This is not a BraintreeError; blocked by braintree-request refactor.
        callback(err);
      }

      return;
    }

    try {
      client = new Client(configuration);
    } catch (clientCreationError) {
      callback(clientCreationError);
      return;
    }

    callback(null, client);
  });
}

module.exports = {
  create: create,
  /** @property {string} VERSION the current version of the SDK */
  VERSION: packageVersion
};