UNPKG

savant-cli

Version:
79 lines (65 loc) 1.81 kB
'use strict'; var request = require('request') , utils = require('./utils') , fs = require('fs') , path = require('path'); var ApiClient = module.exports = exports = function(realm) { this.realm = realm; }; ApiClient.getClient = function(dir, cb) { if (typeof(dir) == 'function') { cb = dir; dir = process.cwd(); } fs.readFile(path.join(dir, 'savant.json'), 'utf-8', function(err, text) { if (err) return cb(err); try { cb(null, new ApiClient(JSON.parse(text))); } catch (e) { cb(e); } }); }; Object.defineProperty(ApiClient.prototype, 'baseUrl', { get: function() { return 'http://' + this.realm.host + '/api/v1'; } }); Object.defineProperty(ApiClient.prototype, 'headers', { get: function() { var publicKey = this.realm.publicKey , privateKey = this.realm.privateKey , nonce = utils.randomString(32) , token = utils.sha256(nonce + ':' + privateKey); return { 'API-Auth-PublicKey': publicKey, 'API-Auth-Nonce': nonce, 'API-Auth-Token': token }; } }); ApiClient.prototype.url = function(url) { var cli = this; return cli.baseUrl + '/' + url.replace(/^\//, ''); }; ApiClient.prototype.request = function(method, url, data) { var cli = this; return request.defaults({ method: method ? method.toLowerCase() : undefined, url: url ? cli.url(url) : undefined, headers: cli.headers, body: data }); }; ApiClient.prototype.json = function(method, url, data, cb) { if (typeof(data) == 'function') { cb = data; } this.request(method, url, data)({ json: true }, cb); }; ApiClient.prototype.get = function(url, data, cb) { return this.json('get', url, data, cb); }; ApiClient.prototype.post = function(url, data, cb) { return this.json('post', url, data, cb); };