all files / hapigerjs/lib/ driver-client.js

72% Statements 36/50
54.17% Branches 13/24
70% Functions 7/10
72% Lines 36/50
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89                                                                                                         
'use strict';
 
var Bluebird = require('bluebird');
var request = Bluebird.promisifyAll(require('request'));
var _ = require('lodash');
 
function Driver(options) {
	if (!options) {
		throw new Error('Missing Options for driver, specify -> {url:url,port:port}');
	}
	this.options = _.assign({
		url: options.url || process.env.HAPIGERJS_URL || "http://localhost",
		port: options.port || process.env.HAPIGERJS_PORT || "3456"
	}, options);
	Eif (!this.options.url) {
		console.log('Using default URL http://localhost');
		this.options.url = "http://localhost";
	}
	Eif (!this.options.port) {
		console.log('Using default PORT 3456');
		this.options.port = "3456";
	}
	this.queryUrl = this.options.url + ':' + this.options.port;
}
 
Driver.prototype.POST = function (target, options, callback) {
	var url = this.queryUrl + target;
	var json = JSON.stringify(options);
	return request.postAsync({url: url, body: json}).then(function (result) {
		var json = JSON.parse(result['body']);
		Iif (_.isFunction(callback)) {
			callback(null, json);
		} else {
			return json;
		}
	}).catch(function (err) {
		if (_.isFunction(callback)) {
			return callback(err);
		}
		throw err;
	});
};
 
Driver.prototype.GET = function (target, callback) {
	var url = this.queryUrl + target;
	return request.getAsync({
		url: url
	}).then(function (result) {
		var json;
		Iif (_.isFunction(callback)) {
			json = JSON.parse(result['body']);
			callback(null, json);
		} else {
			json = JSON.parse(result['body']);
			return json;
		}
	}).catch(function (err) {
		if (_.isFunction(callback)) {
			callback(err);
		} else {
			throw err;
		}
	});
};
 
Driver.prototype.DELETE = function (target, callback) {
	var url = this.queryUrl + target;
	return request.delAsync({
		url: url
	}).then(function (result) {
		var json;
		Iif (_.isFunction(callback)) {
			json = JSON.parse(result['body']);
			callback(null, json);
		} else {
			json = JSON.parse(result['body']);
			return json;
		}
	}).catch(function (err) {
		if (_.isFunction(callback)) {
			callback(err);
		} else {
			throw err;
		}
	});
};
 
module.exports = Driver;