{"size": 1625, "ext": "js", "max_stars_repo_path": "src/client.js", "max_stars_repo_name": "vogdb/pulsar-rest-api-client-node", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/client.js", "max_issues_repo_name": "vogdb/pulsar-rest-api-client-node", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/client.js", "max_forks_repo_name": "vogdb/pulsar-rest-api-client-node", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.9594594595, "max_line_length": 72, "alphanum_fraction": 0.592}
var _ = require('underscore');
var Promise = require('bluebird');
var Rest = require('./rest');
var Websocket = require('./websocket');

/**
 * @param {String} url
 * @param {String} token
 * @constructor
 */
function Client(url, token) {
  this._rest = new Rest(url, token);
  this._websocket = new Websocket(url, token);
}

/**
 * @returns {Promise}
 */
Client.prototype.connect = function() {
  return this._websocket.connect();
};

/**
 * @param {Job} job
 * @return {Promise}
 */
Client.prototype.runJob = function(job) {
  var postData = {task: job.task};
  if (job.taskVariables && !_.isEmpty(job.taskVariables)) {
    postData.taskVariables = job.taskVariables;
  }
  return this._rest.request("/" + job.app + "/" + job.env, {
      method: 'POST',
      body: postData,
      json: true
    })
    .then(function(jobData) {
      if (jobData.id) {
        job.setData(jobData);
        this._websocket.addJob(job);
        job.emit('create');
        return job;
      } else {
        var error = new Error('Got empty job id. Job was not created.');
        job.emit('error', error);
        throw error;
      }
    }.bind(this))
    .catch(function(error) {
      job.emit('error', error);
      throw error;
    });
};

/**
 *
 * @param {Job} job
 * @returns {Promise}
 */
Client.prototype.killJob = function(job) {
  if (!job || !job.data || !job.data.id) {
    return Promise.reject(new Error('Invalid job'));
  }
  return this._rest.request("/job/" + job.data.id + "/kill", {
    method: 'POST'
  });
};

Client.prototype.jobs = function() {
  return this._rest.request('/jobs');
};

module.exports = Client;
