diff --git a/src/.jshintrc b/src/.jshintrc new file mode 100644 index 0000000..51ef6e9 --- /dev/null +++ b/src/.jshintrc @@ -0,0 +1,22 @@ +{ + "bitwise": true, + "curly": true, + "eqeqeq": true, + "es5": true, + "latedef": true, + "maxcomplexity": 10, + "maxdepth": 5, + "maxlen": 80, + "maxparams": 4, + "maxstatements": 15, + "newcap": true, + "node": true, + "noempty": true, + "nonew": true, + "quotmark": true, + "smarttabs": true, + "strict": false, + "trailing": true, + "undef": true, + "unused": true +} diff --git a/src/response.js b/src/response.js new file mode 100644 index 0000000..6c94e8d --- /dev/null +++ b/src/response.js @@ -0,0 +1,31 @@ +function Response(transport, id) +{ + this.transport = transport; + this.id = id; +} + +Response.prototype.sendResult = function (value) +{ + this.transport(JSON.stringify({ + 'jsonrpc': '2.0', + 'result': value, + 'id': this.id, + })); + + // Prevents results/errors to be sent more than once. + delete this.transport; +}; + +Response.prototype.sendError = function (error) +{ + this.transport(JSON.stringify({ + 'jsonrpc': '2.0', + 'error': error, + 'id': this.id, + })); + + // Prevents results/errors to be sent more than once. + delete this.transport; +}; + +module.exports = Response; diff --git a/src/xapi.js b/src/xapi.js new file mode 100644 index 0000000..74b0ebf --- /dev/null +++ b/src/xapi.js @@ -0,0 +1,50 @@ +var Q = require('q'); +var xmlrpc = require('xmlrpc'); + +function Xapi(host) +{ + // Parent constructor. + Xapi.super_.call(this); + + this.xmlrpc = xmlrpc.createSecureClient({ + hostname: host, + port: '443', + rejectUnauthorized: false, + }); // @todo Handle connection success/error. + + this.errors = []; +} +require('util').inherits(Xapi, require('events').EventEmitter); + +Xapi.prototype.call = function (method) { + var params = Array.prototype.slice.call(arguments, 1); + + if (this.sessionId) + { + params.unshift(this.sessionId); + } + + var self = this; + return Q.ninvoke(this.xmlrpc, 'methodCall', method, params) + .then(function (value) { + if ('Success' !== value.Status) + { + throw value; + } + + return value.Value; + }) + .fail(function (error) { + self.errors.push(error); + throw error; + }); +}; + +Xapi.prototype.connect = function (username, password) { + var self = this; + + return this.call('session.login_with_password', username, password) + .then(function (session_id) { + self.sessionId = session_id; + }); +};