UNPKG

eduterra-cli

Version:
77 lines (66 loc) 1.88 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, 'eduterra.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 () { var protocol = this.realm.secure ? 'https' : 'http'; return protocol + '://' + 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() : null, url: url ? cli.url(url) : null, 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); };