save-point

This commit is contained in:
Spencer Alger
2013-09-16 13:45:17 -07:00
parent 69b2e44613
commit a305581d9c
43 changed files with 694 additions and 578 deletions

4
.gitmodules vendored
View File

@ -1,3 +1,3 @@
[submodule "api_spec"]
path = api_spec
[submodule "spec/es_api"]
path = spec/es_api
url = git@github.com:elasticsearch/elasticsearch-rest-api-spec.git

View File

@ -1,2 +0,0 @@
node_modules/*
dist/*

View File

@ -34,42 +34,32 @@ module.exports = function (grunt) {
dest: 'dist/elasticsearch-node.js'
}
},
nodeunit: {
files: ['test/**/*.js']
mochaTest: {
test: {
options: {
reporter: 'spec',
require: [
'should'
]
},
src: ['spec/**/*.js']
}
},
jshint: {
files: ['Gruntfile.js', '<%= concat.node.dest %>', 'test/**/*.js' ],
cwd: 'src',
files: ['../Gruntfile.js', '**/*.js' ],
options: {
bitwise: true,
curly: true,
eqeqeq: true,
immed: true,
indent: 2,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
globalstrict: true,
devel: true,
node: true,
globals: {
exports: true,
module: false
}
jshintrc: 'src/.jshintrc'
}
}
});
// load plugins
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Default task.
grunt.registerTask('default', ['concat','nodeunit','jshint']);
grunt.registerTask('default', [/*'jshint',*/ 'mochaTest']);
};

View File

@ -10,7 +10,15 @@
"grunt-contrib": "~0.7.0",
"grunt-contrib-concat": "~0.3.0",
"grunt-contrib-jshint": "~0.6.0",
"grunt-contrib-nodeunit": "~0.2.0"
"grunt-contrib-nodeunit": "~0.2.0",
"mocha": "~1.12.1",
"grunt-mocha-test": "~0.6.3",
"should": "~1.3.0"
},
"license": "Apache License"
"license": "Apache License",
"dependencies": {
"lodash": "~2.0.0",
"require-directory": "~1.1.1",
"cli-color": "~0.2.3"
}
}

View File

View File

@ -1,32 +1,32 @@
{
"browser": true,
"node": true,
"bitwise":false,
"bitwise": false,
"curly": true,
"eqnull": true,
"globalstrict": true,
"devel": true,
"eqeqeq": true,
"forin": false,
"forin": true,
"immed": true,
"supernew": true,
"expr": true,
"expr": false,
"indent": 2,
"latedef": true,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"noempty": true,
"undef": true,
"quotmark": "single",
"plusplus": false,
"boss": true,
"trailing": false,
"trailing": true,
"laxbreak": true,
"laxcomma": true,
"validthis": true,
"sub": true,
"maxlen": 140,
"globals": {
"define": true,
"require": true
"describe": true,
"it": true,
"beforeEach": true
}
}

1
spec/es_api Submodule

Submodule spec/es_api added at 9831a98e42

View File

@ -0,0 +1,40 @@
/* JSON Serializer tests */
var JsonSerializer = require('../../src/lib/serializers/Json');
describe('json serializer', function () {
var json;
beforeEach(function () {
json = new JsonSerializer();
});
it('creates simple json strings', function () {
json.serialize({foo: true}).should.eql('{"foo":true}');
});
it('creates pretty json strings', function () {
json.serialize({foo: true, bake: 'cake', 'with': ['bacon']}, null, ' ')
.should.eql(['{',
' "foo": true,',
' "bake": "cake",',
' "with": [',
' "bacon"',
' ]',
'}'].join('\n'));
});
it('reads simple json strings', function () {
json.unserialize('{"foo":true}').should.eql({ foo: true });
});
it('does not create date objects', function () {
json
.unserialize('{"date":"2012-04-23T18:25:43.511Z"}')
.should.eql({
date: '2012-04-23T18:25:43.511Z'
});
});
});

View File

@ -5,26 +5,6 @@
var esj = require('../../dist/elasticsearch-node.js');
var _c = new esj.Client();
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.transportNode = {
setUp: function(done) {
done();

28
src/.jshintrc Normal file
View File

@ -0,0 +1,28 @@
{
"node": true,
"white": true,
"bitwise": false,
"curly": true,
"eqnull": true,
"eqeqeq": true,
"forin": true,
"immed": true,
"expr": false,
"indent": 2,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"noempty": true,
"undef": true,
"quotmark": "single",
"plusplus": false,
"boss": true,
"trailing": true,
"laxbreak": true,
"laxcomma": true,
"validthis": true,
"sub": true,
"maxlen": 140
}

View File

@ -1,16 +0,0 @@
/*
*/
// Expose the client object
esj.Client = function(options) {
this.options = options || {};
// For convience
this.transport = this.options.transport || new esj.Transport(this.options);
this.logger = this.options.logger || new esj.Log(this.transport);
this.tracer = this.options.tracer || new esj.Trace(this.transport);
this.serializer = this.options.serializer || new esj.Serializer.json();
};

5
src/elasticsearch.js Normal file
View File

@ -0,0 +1,5 @@
var es = {
Client: require('./lib/client')
};
module.exports = es;

17
src/lib/Client.js Normal file
View File

@ -0,0 +1,17 @@
var _ = require('./Utils')
, transports = _.requireDir(module, './transports');
// Expose the client object
function Client(config) {
config = _.defaults(config || {}, {
logger: 'warning'
});
// For convenience
// this.transport = this.options.transport || new transports.NodeHttp(this.options);
this.logger = config.logger || new es.Log(this.logger);
// this.serializer = this.options.serializer || new es.Serializer.json();
}
module.exports = Client;

42
src/lib/Interfaces.js Normal file
View File

@ -0,0 +1,42 @@
var _ = require('./Utils')
, TransportAbstract = require('./transports/TransportAbstract');
function Interface(methods, properties) {
this.methods = methods;
this.properties = properties;
}
Interface.properties.implementedBy = function (object) {
var i;
if (this.methods) {
for (i = 0; i < this.methods.length; i++) {
if (!object[this.methods[i]] || typeof object[this.methods[i]] !== 'function') {
return false;
}
}
}
};
var Transport = new Interface(
[// methods
''
],
{// properties
'': ''
}
);
var Client = new Interface(
[
''
],
{
transport: Transport
}
);
module.exports = {
Transport: Transport,
Client: Client
};

167
src/lib/Log.js Normal file
View File

@ -0,0 +1,167 @@
var _ = require('../Utils'),
events = require('events'),
loggers = _.requireDir(module, './loggers');
/**
*
* Log bridge, which writes using one or more Logger's. Setup these loggers by
* specifying their config with the first argument, or by calling addOutput.
*
* @constructor
* @extends {@link events.EventEmitter}
*
* @param {string|Object|(string|Object)[]} output - Either the level to setup a single logger, a
* full config object for alogger, or an array of config objects to use for creating log outputs.
* @param {string} output.level - One of the keys in {@link Log.levels} (error, warning, etc.)
* @param {string} output.type - The name of the logger to use for this output
*/
function Log(output) {
var i;
output = output || 2;
if (_.isString(output)) {
output = [
{
level: output
}
];
} else if (_.isObject(output)) {
output = [output];
} else if (_.isArray(output)) {
for (i = 0; i < output.length; i++) {
if (_.isString(output[i])) {
output[i] = {
level: output[i]
};
}
}
}
if (!_.isArrayOfObjects(output)) {
throw new TypeError('Invalid Logging output config');
}
/**
* A list of the log streams, which are listening to this logger.
* @type {Array}
*/
this.outputs = [];
for (i = 0; i < output.length; i++) {
this.addLogger(output[i]);
}
}
_.inherits(Log, events.EventEmitter);
/**
* Levels observed by the loggers, with their rank
* @type {Object}
*/
Log.levels = {
// unexpected exceptions and 500s
error: 1,
// correctly formatted error responses from ES (400, ...) and recoverable errors (one node unresponsive)
warning: 2,
// info on what's going on (sniffing etc)
info: 3,
// all requests with query params and no data, response codes & exec times
debug: 4,
// body and response for all requests
trace: 5
};
Log.levelsInverted = _.invert(Log.levels);
/**
* Converts a log identifier to an integer representing it's level
* @private
* @param {*} ident - The identifying to convert, if invalid then the default will be returned
* @param {Integer} default - The default log level to use if the identifier is not valid
* @return {Integer} - The number reprsenting the log level
*/
Log.level = function (ident, def) {
if (_.has(Log.levelsInverted, ident)) {
return _.parseInt(ident);
} else {
if (_.has(Log.levels, ident)) {
return Log.levels[ident];
} else {
return def;
}
}
};
/**
* Create a new logger, based on the config.
* @param {object} config An object with config options for the logger. Type is used to find the
* logger class, and should be one of 'file' or 'stdio' if running in node.js,
* or one of 'console' or 'html' if running in the browser.
* @return {undefined}
*/
Log.prototype.addOutput = function (config) {
_.defaults(config, {
type: 'stdio',
level: Log.level(config.type, 2)
});
if (loggers[config.type]) {
return this.outputs[this.outputs.push(new loggers[config.type](config, this)) - 1];
} else {
throw new TypeError('Invalid logger type ' + config.type);
}
};
/**
* Log an error
* @param {Error/String} error The Error to log
* @return {undefined}
*/
Log.prototype.error = function (e) {
this.emit('error', e instanceof Error ? e : new Error(e));
};
/**
* Log a warning message
* @param {String} message The warning message
* @return {undefined}
*/
Log.prototype.warning = function (message) {
this.emit('warning', message);
};
/** @alias Log.warning */
Log.prototype.warn = Log.prototype.warning;
/**
* Log useful info about what's going on
* @param {String} message The warning message
* @return {undefined}
*/
Log.prototype.info = function (message) {
this.emit('info', message);
};
/**
* Log a debug level message
* @param {String} message The warning message
* @return {undefined}
*/
Log.prototype.debug = function (message) {
this.emit('debug', message);
};
/**
* Log a trace level message
* @param {String} message The warning message
* @return {undefined}
*/
Log.prototype.trace = function (message) {
this.emit('trace', message);
};
module.exports = Log;

41
src/lib/Transport.js Normal file
View File

@ -0,0 +1,41 @@
var _ = require('./Utils')
, selectors = require('./selector');
var configDefaults = {
hosts : [
{
host: 'localhost',
port: 9200
}
],
//nodes_to_host_callback : construct_hosts_list,
sniff_on_start : false,
sniff_after_requests : 0,
sniff_on_connection_fail : false,
max_retries : 3,
selector : 'roundRobin'
};
function Transport(config) {
// These are all unique to each instance of client
config = _.defaults(config || {}, configDefaults);
if (_.isFunction(this.opts.selector)) {
this.selector = this.opts.selector;
} else if (_.has(selectors, this.opts.selector)) {
this.selector = selectors[this.opts.selector];
} else {
throw new Error('Invalid Selector, specify a function or selector name.');
}
}
/**
* Modify the defaults for the Transport class
* @param {Object} update An object representing the changes to be made to the defaults.
* @static
* @return {undefined}
*/
Transport.defaults = function (update) {
_.assign(configDefaults, update);
};

43
src/lib/Utils.js Normal file
View File

@ -0,0 +1,43 @@
var _ = require('lodash')
, path = require('path')
, requireDir = require('require-directory');
// mix in the node utils
_.mixin(require('util'));
var mixins = {};
/**
* [joinPath description]
* @type {[type]}
*/
mixins.joinPath = path.join;
/**
* Require all of the modules in a directory
* @param {Module} module The module object which will own the required modules.
* @param {String} path Path to the directory which will be traversed
*/
mixins.requireDir = requireDir;
/**
* isArrayOf(Strings|Objects|Arrays|Finites|Functions|RegExps)
* @param {Array} arr An array to validate
* @return {Boolean}
*/
'String Object Array Finite Function RegExp'.split(' ').forEach(function (type) {
var check = _.bind(_['is' + type], _)
// used to find the first value that isn't of the sub type specified
, checkForNotType = function (val) { return !check(val); };
mixins['isArrayOf' + type + 's'] = function (arr) {
// quick shallow check of arrays
return _.isArray(arr) && !_.find(arr.slice(0, 10), checkForNotType);
};
});
_.mixin(mixins);
module.exports = _;

6
src/lib/loggers/File.js Normal file
View File

@ -0,0 +1,6 @@
function File(config) {
}
module.exports = File;

123
src/lib/loggers/StdIo.js Normal file
View File

@ -0,0 +1,123 @@
var clc = require('cli-color')
, Log = require('../Log')
, _ = require('../Utils');
/**
* Special version of the Stream logger, which logs errors and warnings to stderr and all other
* levels to stdout.
* @param {Object} config - The configuration for the Logger
* @param {string} config.level - The highest log level for this logger to output. See {@link Log.levels}
* @param {Log} bridge - The object that triggers logging events, which we will record
*/
function StdIo(config, bridge) {
this.bridge = bridge;
var i, method;
var handlers = this.handlers = {};
_.each(Log.levels, function (i, name) {
// create a version of each log event handler that is bound to "this"
handlers[Log.levels[name]] = 'on' + name.subString(0, 1).toUpperCase() + name.subString(1).toLowerCase();
});
this.setupListeners(config.level);
}
/**
* Clear the current event listeners and then re-listen for events based on the level specified
* @param {Integer} level - The max log level that this logger should listen to
* @return {undefined}
*/
StdIo.prototype.setupListeners = function (level) {
this.removeListeners();
for (this.listeningLevel = level; level > 0; level--) {
this.bridge.on(Log.levelsInverted[level], this.handlers[level]);
}
};
/**
* Clear the current event listeners
* @return {undefined}
*/
StdIo.prototype.cleanUpListeners = function () {
for (; this.listeningLevel < 0; this.listeningLevel--) {
// remove the listeners for each event
this.bridge.removeListener(Log.levelsInverted[this.listeningLevel], this.handlers[this.listeningLevel]);
}
};
/**
* Combine the array_like param into a simple string
* @param {Array|Object} array_like - An array like object that can be itterated by _.each
* @return {String} - The final string.
*/
function join(array_like) {
return _.map(array_like, function (item) {
if (_.isPlainObject(item)) {
return _.inspect(item, { showHidden: true, depth: null, color: true}) + '\n';
} else {
return item.toString();
}
}).join(' ');
}
/**
* Sends output to a stream, does some formatting first
* @param {WriteableStream} to - The stream that should receive this message
* @param {String} label - The text that should be used at the begining of the message
* @param {function} colorize - A function that recieves a string and returned a colored version of it
* @param {*} what - The message to log
* @return {undefined}
*/
StdIo.prototype.write = function (to, label, colorize, what) {
if (this.color) {
label = colorize(label);
}
to.write(label + ': ' + (typeof what === 'object' ? join(what) : what));
};
/**
* Handler for the bridges "error" event
* @param {Error} e - The Error object to log
* @return {undefined}
*/
StdIo.prototype.onError = function (e) {
this.write(process.strderr, 'ERROR', clc.red.bold, e.name + ': ' + e.message + '\nStack Trace:\n' + e.stack);
};
/**
* Handler for the bridges "warning" event
* @param {...*} msg - Any amount of messages that will be joined before logged
* @return {undefined}
*/
StdIo.prototype.onWarning = function (/* ...msg */) {
this.write(process.strderr, 'warning', clc.yellow.bold, arguments);
};
/**
* Handler for the bridges "info" event
* @param {...*} msg - Any amount of messages that will be joined before logged
* @return {undefined}
*/
StdIo.prototype.onInfo = function (/* ...msg */) {
this.write(process.stdout, 'INFO', clc.cyan.bold, arguments);
};
/**
* Handler for the bridges "debug" event
* @param {...*} msg - Any amount of messages that will be joined before logged
* @return {undefined}
*/
StdIo.prototype.onDebug = function (/* ...msg */) {
this.write(process.stdout, 'DEBUG', clc.magentaBright.bold, arguments);
};
/**
* Handler for the bridges "trace" event
* @param {...*} msg - Any amount of messages that will be joined before logged
* @return {undefined}
*/
StdIo.prototype.onTrace = function (/* ...msg */) {
this.write(process.stdout, 'TRACE', clc.cyanBright.bold, arguments);
};
module.exports = StdIo;

14
src/lib/loggers/Stream.js Normal file
View File

@ -0,0 +1,14 @@
/** @module StreamLogger */
/**
* A logger object, which listens to the LogBridge for logging events based on it's config. This
* logger writes it logs to any [WriteableStream]{@link http://nodejs.org/api/stream.html#stream_class_stream_writable_1}.
* @constructor
* @param {Object} config A hash of the config options
* @param {[type]} logBridge [description]
*/
function Stream(config, logBridge) {
this.setLevel(config.level);
}
module.exports = Stream;

View File

@ -0,0 +1,9 @@
var _ = require('../Utils');
function Random() {}
Random.prototype.select = function (connections) {
return _.shuffle(connections).unshift();
};
module.exports = Random;

View File

@ -0,0 +1,8 @@
function RoundRobin() {}
RoundRobin.prototype.select = function (connections) {
connections.unshift(connections.pop());
return connections[0];
};
module.exports = RoundRobin;

View File

@ -0,0 +1,11 @@
/* JSON serializer */
var _ = require('../Utils');
function Json() {}
Json.prototype.serialize = _.bind(JSON.stringify, JSON);
Json.prototype.unserialize = _.bind(JSON.parse, JSON);
module.exports = Json;

View File

@ -0,0 +1,17 @@
/* JSON serializer */
var _ = require('lodash');
function QueryString() {}
QueryString.prototype.serialize = function (obj) {
return JSON.stringify(obj);
};
// TODO: real query string parsing... there is a well tested module for this :P
QueryString.prototype.unserialize = function (string) {
return _.object(_.map(_.map(string.split('&'), function splitOnEqlAndDecode(string) {
return _.map(string.split('='), decodeURIComponent);
})));
};
module.exports = QueryString;

View File

@ -0,0 +1,74 @@
/* elasticsearch-js nodejs transport */
var http = require('http');
function NodeHttp() {
// Split hostname:port into its repective parts
function splitHost(u) {
var s = u.split(':');
return {host: s[0], port: s[1]};
}
// Meta function for handling any http request that can have a body (PUT,POST,DELETE)
function performRequest(context, method, path, params, body, successcb, errorcb, retries) {
var
//context = context,
host = splitHost(context.selector(context.options.hosts)),
options = {
host: host.host,
port: host.port,
path: path + '?' + _.toQueryString(params),
method: method,
headers: {
'Content-Type': 'application/json'
}
};
var request = http.request(options, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (d) {
data = data + d;
});
res.on('end', function () {
var response = {
data : data.charAt(0) === '{' ? JSON.parse(data) : data,
headers : res.headers,
status : res.statusCode
};
if (successcb != null && response.status < 300) {
successcb(response);
} else if (errorcb != null) {
errorcb(response);
}
});
});
if (errorcb != null) {
request.on('error', errorcb);
}
if(method !== 'GET' && method !== 'HEAD') {
request.write(body);
}
request.end();
};
// Public functions
return {
get : _.bind(performRequest, this, 'PUT'),
put : _.bind(performRequest, this, 'POST'),
post : _.bind(performRequest, this, 'DELETE'),
del : _.bind(performRequest, this, 'GET'),
head : _.bind(performRequest, this, 'HEAD')
};
} ());

View File

@ -0,0 +1,9 @@
function TransportAbstract() {
}
TransportAbstract.prototype = {
};
module.exports = TransportAbstract;

View File

View File

@ -1,72 +0,0 @@
/**
*
* esj.Log is a basic logger with error, warn, info and debug levels
*
* @typedef {Object} Log
* @param {Transport} transport the transport ob
*
* @property {Object} options The options passed and merged with defaults
* @property {Transport} transport The esj.Transport for this Log
*
*/
esj.Log = function(transport,options) {
options = options || {};
var _d = {
error : true,
warn : true,
info : false,
debug : false
};
this.options = defaults(options,_d);
this.transport = transport;
};
esj.Log.prototype = (function() {
var error = function(m) {
if (this.options.error) {
console.error(m);
return m;
} else {
return false;
}
};
var warn = function(m) {
if (this.options.warn){
console.warn(m);
return m;
} else {
return false;
}
};
var info = function(m) {
if (this.options.info){
console.info(m);
return m;
} else {
return false;
}
};
var debug = function(m) {
if (this.options.debug){
console.log(m);
return m;
} else {
return false;
}
};
return {
error : error,
warn : warn,
info : info,
debug : debug
};
} ());

View File

@ -1,38 +0,0 @@
esj.Trace = function(transport,options) {
options = options || {};
var _d = {
info : false,
trace : false
};
this.options = defaults(options,_d);
this.transport = transport;
};
// TODO: Make this properly format the messages. Implement helper methods
esj.Trace.prototype = (function() {
var info = function(msg) {
if (this.options.info){
console.info(this.transport.options.hosts+" "+msg);
return msg;
} else {
return false;
}
};
var trace = function(msg) {
if (this.options.debug) {
console.log(this.transport.options.hosts+" "+msg);
return msg;
} else {
return false;
}
};
return {
info : info,
trace : trace
};
} ());

View File

@ -1,3 +0,0 @@
}).call(this);

View File

@ -1,20 +0,0 @@
(function() {
'use strict';
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// save the previous version of ejs
var _esj = root && root.esj,
esj;
// Create the esj object
if (typeof exports !== 'undefined') {
esj = exports;
} else {
esj = root.ejs = {};
}

View File

@ -1,12 +0,0 @@
/* Host selectors */
esj.Selector = {
roundRobin : function(hosts) {
hosts.unshift(hosts.pop());
return hosts[0];
},
random : function(hosts) {
hosts = shuffle(hosts);
return hosts[0];
}
};

View File

@ -1,3 +0,0 @@
/* Generic serializer, does nothing */
esj.Serializer = {};

View File

@ -1,17 +0,0 @@
/* JSON serializer */
esj.Serializer.json = function() {};
esj.Serializer.json.prototype = (function() {
return {
dump : function(obj) {
return JSON.stringify(obj);
},
load : function(string) {
return JSON.parse(string);
}
};
} ());

View File

@ -1,124 +0,0 @@
// (c) 2013 Rashid Khan, Elasticsearch BV
// Portions of this file are borrowed from Underscore js,
// Set the aliases that underscore uses
var
slice = Array.prototype.slice,
toString = Object.prototype.toString,
hasOwnProp = Object.prototype.hasOwnProperty,
nativeForEach = Array.prototype.forEach,
nativeIsArray = Array.isArray,
nativeIndexOf = Array.prototype.indexOf,
has,
each,
defaults,
extend,
indexOf,
isUndefined,
shuffle,
queryString,
breaker = {};
// Has own property?
has = function (obj, key) {
return hasOwnProp.call(obj, key);
};
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
each = function (obj, iterator, context) {
if (obj == null) {
return;
}
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) {
return;
}
}
} else {
for (var key in obj) {
if (has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) {
return;
}
}
}
}
};
// Fill in a given object with default properties.
defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Extend a given object with all the properties in passed-in object(s).
extend = function (obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
// Returns the index at which value can be found in the array, or -1 if
// value is not present in the array.
indexOf = function (array, item) {
if (array == null) {
return -1;
}
var i = 0, l = array.length;
if (nativeIndexOf && array.indexOf === nativeIndexOf) {
return array.indexOf(item);
}
for (; i < l; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
};
// Is an object undefined?
isUndefined = function(obj) {
return obj === void 0;
};
// shuffle an array
shuffle = function(obj) {
var shuffled = [], rand;
each(obj, function(value, index, list) {
if (index === 0) {
shuffled[0] = value;
} else {
rand = Math.floor(Math.random() * (index + 1));
shuffled[index] = shuffled[rand];
shuffled[rand] = value;
}
});
return shuffled;
};
// Takes an object and makes it into a query string
queryString = function(obj) {
var str = [];
each(obj,function(v,k){
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
});
return str.join("&");
};

View File

@ -1,22 +0,0 @@
esj.Transport = function (options) {
options = options || {};
var _d = {
hosts : ['localhost:9200'],
//nodes_to_host_callback : construct_hosts_list,
sniff_on_start : false,
sniff_after_requests : 0,
sniff_on_connection_fail : false,
max_retries : 3,
selector : esj.Selector.roundRobin
};
// These are all unique to each instance of client
this.options = defaults(options,_d);
// For conviences
this.selector = this.options.selector;
};

View File

@ -1,81 +0,0 @@
/* elasticsearch-js nodejs transport */
var http = require('http');
esj.Transport.prototype = (function() {
// Split hostname:port into its repective parts
var splitHost = function(u) {
var s = u.split(':');
return {host:s[0],port:s[1]};
};
// Meta function for handling any http request that can have a body (PUT,POST,DELETE)
var performRequest = function (context,method, path, params, body, successcb, errorcb, retries) {
var
//context = context,
host = splitHost(context.selector(context.options.hosts)),
options = {
host: host.host,
port: host.port,
path: path + '?' + queryString(params),
method: method,
headers: {
'Content-Type': 'application/json'
}
};
var request = http.request(options, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (d) {
data = data + d;
});
res.on('end', function () {
var response = {
data : data.charAt(0) === '{' ? JSON.parse(data) : data,
headers : res.headers,
status : res.statusCode
};
if (successcb != null && response.status < 300) {
successcb(response);
} else if (errorcb != null) {
errorcb(response);
}
});
});
if (errorcb != null) {
request.on('error', errorcb);
}
if(method !== 'GET' && method !== 'HEAD') {
request.write(body);
}
request.end();
};
// Aliases to performRequest
var put = function (path, params, body, successcb, errorcb) {performRequest(this, 'PUT', path, params, body, successcb, errorcb);};
var post = function (path, params, body, successcb, errorcb) {performRequest(this, 'POST', path, params, body, successcb, errorcb);};
var del = function (path, params, body, successcb, errorcb) {performRequest(this, 'DELETE', path, params, body, successcb, errorcb);};
var get = function (path, params, body, successcb, errorcb) {performRequest(this, 'GET', path, params, body, successcb, errorcb);};
var head = function (path, params, body, successcb, errorcb) {performRequest(this, 'GET', path, params, body, successcb, errorcb);};
// Public functions
return {
get : get,
put : put,
post : post,
del : del,
head : head
};
} ());

View File

@ -1,39 +0,0 @@
/* Serializer tests */
'use strict';
var esj = require('../dist/elasticsearch-node.js');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.serializer = {
setUp: function(done) {
// setup here
done();
},
'json': function(test) {
test.expect(2);
// Create serializer object
var _s = new esj.Serializer.json();
test.equal(_s.dump({foo:true}), '{"foo":true}', 'should be \'{"foo":true}\'');
test.deepEqual(_s.load('{"foo":true}'), {foo:true}, 'should be {foo:true}');
test.done();
},
};

View File

@ -1,68 +0,0 @@
/* Shared tests */
/*
'use strict';
//var esj = require('../dist/elasticsearch-node.js');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
exports.shared = {
setUp: function(done) {
// setup here
done();
},
'defaults': function(test) {
test.expect(1);
test.deepEqual(defaults({foo:1,bar:2},{bar:3,baz:4}),{foo:1,bar:2,baz:4},'should be foo:1,bar:2,baz:4')
test.done();
},
'extend': function(test) {
test.expect(1);
test.deepEqual(extend({foo:1},{bar:2}),{foo:1,bar:2},'should be foo:1,bar:2')
test.done();
},
'indexOf': function(test) {
test.expect(1);
test.equal(indexOf([1,2,3],3), 2, 'should be 2')
test.done();
},
'queryString': function(test) {
test.expect(1);
test.equal(queryString({foo:'bar'}),'foo=bar','should be foo=bar')
test.done();
},
'has': function(test) {
test.expect(1);
test.equal(has({foo:1},'foo'),true,'should be true')
test.done();
},
'each': function(test) {
test.expect(1);
var str = '';
each([1,2,3],function(v){str+=v;})
test.equal(str,'123','should be 123')
test.done();
},
'isUndefined': function (test) {
test.expect(1);
test.ok(isUndefined(undefined),'should be undefined')
test.done();
}
};
*/