<commit_before>var Db = require("mongodb").Db,
    Server = require("mongodb").Server,
    Promise = global.Packages.Promise;

function getClient(server, pools, callback) {
    var poolkey = server.host + ":" + server.port;
    var pool = pools[poolkey];

    if (!pool) {
        var db = new Db(server.db, new Server(server.host, server.port, {
            auto_reconnect: true
        }), {
            native_parser: true,
            w: 1
        });

        db.open(function(err, mongoclient) {
            if (err) {
                callback(err);
                return;
            }
            pools[poolkey] = mongoclient;
            callback(err, pools[poolkey]); //return Promise
        });
    }
    else {

        callback(null, pool);
    }

}

function initialize(params) {

    var pools = [];
    var server = {
        host: params.host,
        port: params.port,
        db: params.db,
    };

    // TODO: Mongo supports sharding and replica logic, we should compline this class to support sharding and read replica

    function deleteAllPropertiesWhichAreUndefined(object){
        for(var k in object){
            if(object[k] === undefined){
                delete object[k];
            }
        }

        return object;
    }

    function extend(attributes) {

        if (!attributes.tableName) {
            throw new Error("tableName must be defined");
        }
        function saveData(context, input) {

            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(context.tableName).save(deleteAllPropertiesWhichAreUndefined(context.getDBObject(input)), function (err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        resolve(output);
                        return;
                    });
                });
            });
        }
        function getArrayQuery(context, data) {
            var query_obj = {};
            data = deleteAllPropertiesWhichAreUndefined(context.getDBObject(data));

            for (var property in data) {
                if (data[property] instanceof Array) {
                    query_obj[property] = { $each: data[property] };
                }
                else {
                    query_obj[property] = data[property];
                }
            }

            return query_obj;
        }

        function Model(obj) {

            //if model creation is not with new keyword then return it with new
            if (!(this instanceof Model)) {
                return new Model(obj);
            }

            this.tableName = attributes.tableName;

            if (attributes.idAttribute) {
                obj._id = obj[attributes.idAttribute];
                obj[attributes.idAttribute] = undefined;
            }

            this.input = obj;
        }

        Model.prototype.update = function update(where_clause, set_fields) {
            var self = this;
            return new Promise(function(resolve, reject) {
                getClient(server, pools,function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(where_clause, /*{
                        $set: set_fields
                    }*/ set_fields, function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        resolve(output);
                        return;
                    });
                });
            });
        };

        Model.prototype.save = function save() {
            var self = this;
            return saveData(self, self.input);

        };

        Model.prototype.saveInBatch = function saveInBatch() {
            var self = this;

            var promises = [];

            for (var index = 0; index < self.input.length; index++) {
                promises.push(saveData(self, self.input[index]));
            }

            return Promise.all(promises).spread(function () { return true; });

        };

        function prepareSelectClause(arg) {
            var select_clause_obj = {};
            for (var i = 0; i < arg.length; i++) {
                select_clause_obj[arg[i]] = "1";
            }
            return select_clause_obj;
        }

        Model.prototype.fetch = function fetch() {
            var self = this;

            var select_clause = prepareSelectClause(arguments);

            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    //  deleting all properties which are undefined because otherwise mongo will make them part of query that results
                    //  inappropriate data
                    var mongo_obj = deleteAllPropertiesWhichAreUndefined(self.getDBObject(self.input));

                    client.collection(self.tableName).find(
                        mongo_obj, select_clause, {
                        limit: 1
                    }).toArray(function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }

                        if (output.length > 0) {
                            resolve(self.getObjectFromDBObject(output.shift()));
                            return;
                        }
                        else {
                            resolve(null);
                            return;
                        }
                    });
                });
            });
        };

        Model.prototype.getInBatch = function getInBatch() {
            var self = this;
            var select_clause = prepareSelectClause(arguments);

            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).find({
                        _id: {
                            $in: self.input
                        }
                    }, select_clause, {
                        limit: self.input.length
                    }).toArray(function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }

                        var result = [];

                        while (output.length > 0) {
                            result.push(self.getObjectFromDBObject(output.shift()));
                        }
                        resolve(result);
                        return;
                    });
                });
            });
        };

        Model.prototype.find = function find(criteria, select_clause, projection) {
            var self = this;
            select_clause = prepareSelectClause(select_clause);
            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).find(criteria, select_clause, projection).toArray(function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        var result = [];

                        while (output.length > 0) {
                            result.push(self.getObjectFromDBObject(output.shift()));
                        }
                        resolve(result);
                        return;
                    });
                });
            });
        };

        Model.prototype.appendArrayItemsIfNotExist = function appendArrayItemsIfNotExist(where_clause) {
            var self = this;

            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(
                        deleteAllPropertiesWhichAreUndefined(self.getDBObject(where_clause)),
                        { $addToSet: getArrayQuery(self, self.input) }, function (err, output) {
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                        });
                });
            });
        };

        Model.prototype.appendArrayItems = function appednArrayItems(where_clause) {
            var self = this;

            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(
                        deleteAllPropertiesWhichAreUndefined(self.getDBObject(where_clause)),
                        { $push: getArrayQuery(self, self.input) }, function (err, output) {
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                        });
                });
            });
        };

        Model.prototype.getDBObject = function getDBObject(obj) {
            return obj;
        };

        Model.prototype.getObjectFromDBObject = function getObjectFromDBObject(obj) {
            return obj;
        };

        Model.prototype.deleteAll = function deleteAll() {
            var self = this;
            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).remove(err, function (err, output) {
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                        });

                });
            });
        };

        Model.prototype.deleteObject = function deleteObject(){
            var self = this;
            return new Promise(function(resolve, reject){
                getClient(server, pools, function(err, client){
                    if(err){
                        reject(err);
                        return;
                    }

                    var mongo_obj = deleteAllPropertiesWhichAreUndefined(self.getDBObject(self.input));

                    client.collection(self.tableName).remove(mongo_obj, function(err, output){
                        if(err){
                            reject(err);
                            return;
                        }
                        resolve(output);
                        return;
                    });
                });
            });
        };

        Model.prototype.removeArrayItems = function removeArrayItems(where_clause) {
            var self = this;
            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }
                    var db_object = self.getDBObject(where_clause);
                    client.collection(self.tableName).update(
                    db_object, {
                        $pull: db_object
                    }, function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        resolve(output);
                        return;
                    });
                });
            });
        };

        Model.prototype.updateRow = function updateRow(where_clause, set_fields, is_upsert, is_multi){
            var self = this;

            return new Promise(function(resolve, reject){
                getClient(server, pools, function(err, client){
                    if(err){
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(
                        where_clause,
                        set_fields,{ upsert: is_upsert, multi: is_multi },function(err, output){
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                    });
                });
            });
        };

        Model.prototype.findAndModifyRow = function findAndModifyRow(
            query, sort, remove, update, new_data, fields, upsert
            ){
            var self = this;

            return new Promise(function(resolve, reject){
               getclient(server, pools, function(err, client){
                   if(err){
                       reject(err);
                       return;
                   }
                   client.collection(self.tableName).findAndModifyRow(
                       {query: query},
                       {sort: sort},
                       {remove: remove},
                       {update: update},
                       {new: new_data},
                       {fields: fields},
                       {upsert: upsert}, function(err, output){
                           if(err){}
                       });

               });
            });

        };

        return Model;
    }

    return {
        extend: extend

    };
}

module.exports.initialize = initialize;

<commit_msg>removeArrayItem (models/mongo)<commit_after>var Db = require("mongodb").Db,
    Server = require("mongodb").Server,
    Promise = global.Packages.Promise;

function getClient(server, pools, callback) {
    var poolkey = server.host + ":" + server.port;
    var pool = pools[poolkey];

    if (!pool) {
        var db = new Db(server.db, new Server(server.host, server.port, {
            auto_reconnect: true
        }), {
            native_parser: true,
            w: 1
        });

        db.open(function(err, mongoclient) {
            if (err) {
                callback(err);
                return;
            }
            pools[poolkey] = mongoclient;
            callback(err, pools[poolkey]); //return Promise
        });
    }
    else {

        callback(null, pool);
    }

}

function initialize(params) {

    var pools = [];
    var server = {
        host: params.host,
        port: params.port,
        db: params.db,
    };

    // TODO: Mongo supports sharding and replica logic, we should compline this class to support sharding and read replica

    function deleteAllPropertiesWhichAreUndefined(object){
        for(var k in object){
            if(object[k] === undefined){
                delete object[k];
            }
        }

        return object;
    }

    function extend(attributes) {

        if (!attributes.tableName) {
            throw new Error("tableName must be defined");
        }
        function saveData(context, input) {

            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(context.tableName).save(deleteAllPropertiesWhichAreUndefined(context.getDBObject(input)), function (err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        resolve(output);
                        return;
                    });
                });
            });
        }
        function getArrayQuery(context, data) {
            var query_obj = {};
            data = deleteAllPropertiesWhichAreUndefined(context.getDBObject(data));

            for (var property in data) {
                if (data[property] instanceof Array) {
                    query_obj[property] = { $each: data[property] };
                }
                else {
                    query_obj[property] = data[property];
                }
            }

            return query_obj;
        }

        function Model(obj) {

            //if model creation is not with new keyword then return it with new
            if (!(this instanceof Model)) {
                return new Model(obj);
            }

            this.tableName = attributes.tableName;

            if (attributes.idAttribute) {
                obj._id = obj[attributes.idAttribute];
                obj[attributes.idAttribute] = undefined;
            }

            this.input = obj;
        }

        Model.prototype.update = function update(where_clause, set_fields) {
            var self = this;
            return new Promise(function(resolve, reject) {
                getClient(server, pools,function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(where_clause, /*{
                        $set: set_fields
                    }*/ set_fields, function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        resolve(output);
                        return;
                    });
                });
            });
        };

        Model.prototype.save = function save() {
            var self = this;
            return saveData(self, self.input);

        };

        Model.prototype.saveInBatch = function saveInBatch() {
            var self = this;

            var promises = [];

            for (var index = 0; index < self.input.length; index++) {
                promises.push(saveData(self, self.input[index]));
            }

            return Promise.all(promises).spread(function () { return true; });

        };

        function prepareSelectClause(arg) {
            var select_clause_obj = {};
            for (var i = 0; i < arg.length; i++) {
                select_clause_obj[arg[i]] = "1";
            }
            return select_clause_obj;
        }

        Model.prototype.fetch = function fetch() {
            var self = this;

            var select_clause = prepareSelectClause(arguments);

            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    //  deleting all properties which are undefined because otherwise mongo will make them part of query that results
                    //  inappropriate data
                    var mongo_obj = deleteAllPropertiesWhichAreUndefined(self.getDBObject(self.input));

                    client.collection(self.tableName).find(
                        mongo_obj, select_clause, {
                        limit: 1
                    }).toArray(function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }

                        if (output.length > 0) {
                            resolve(self.getObjectFromDBObject(output.shift()));
                            return;
                        }
                        else {
                            resolve(null);
                            return;
                        }
                    });
                });
            });
        };

        Model.prototype.getInBatch = function getInBatch() {
            var self = this;
            var select_clause = prepareSelectClause(arguments);

            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).find({
                        _id: {
                            $in: self.input
                        }
                    }, select_clause, {
                        limit: self.input.length
                    }).toArray(function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }

                        var result = [];

                        while (output.length > 0) {
                            result.push(self.getObjectFromDBObject(output.shift()));
                        }
                        resolve(result);
                        return;
                    });
                });
            });
        };

        Model.prototype.find = function find(criteria, select_clause, projection) {
            var self = this;
            select_clause = prepareSelectClause(select_clause);
            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).find(criteria, select_clause, projection).toArray(function(err, output) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        var result = [];

                        while (output.length > 0) {
                            result.push(self.getObjectFromDBObject(output.shift()));
                        }
                        resolve(result);
                        return;
                    });
                });
            });
        };

        Model.prototype.appendArrayItemsIfNotExist = function appendArrayItemsIfNotExist(where_clause) {
            var self = this;

            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(
                        deleteAllPropertiesWhichAreUndefined(self.getDBObject(where_clause)),
                        { $addToSet: getArrayQuery(self, self.input) }, function (err, output) {
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                        });
                });
            });
        };

        Model.prototype.appendArrayItems = function appednArrayItems(where_clause) {
            var self = this;

            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(
                        deleteAllPropertiesWhichAreUndefined(self.getDBObject(where_clause)),
                        { $push: getArrayQuery(self, self.input) }, function (err, output) {
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                        });
                });
            });
        };

        Model.prototype.getDBObject = function getDBObject(obj) {
            return obj;
        };

        Model.prototype.getObjectFromDBObject = function getObjectFromDBObject(obj) {
            return obj;
        };

        Model.prototype.deleteAll = function deleteAll() {
            var self = this;
            return new Promise(function (resolve, reject) {
                getClient(server, pools, function (err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).remove(err, function (err, output) {
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                        });

                });
            });
        };

        Model.prototype.deleteObject = function deleteObject(){
            var self = this;
            return new Promise(function(resolve, reject){
                getClient(server, pools, function(err, client){
                    if(err){
                        reject(err);
                        return;
                    }

                    var mongo_obj = deleteAllPropertiesWhichAreUndefined(self.getDBObject(self.input));

                    client.collection(self.tableName).remove(mongo_obj, function(err, output){
                        if(err){
                            reject(err);
                            return;
                        }
                        resolve(output);
                        return;
                    });
                });
            });
        };

        Model.prototype.removeArrayItems = function removeArrayItems(where_clause) {
            var self = this;
            return new Promise(function(resolve, reject) {
                getClient(server, pools, function(err, client) {
                    if (err) {
                        reject(err);
                        return;
                    }
                    client.collection(self.tableName).update(
                        deleteAllPropertiesWhichAreUndefined(self.getDBObject(where_clause)),
                        {$pull: getArrayQuery(self, self.input)}, function(err, output) {
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                        });
                });
            });
        };

        Model.prototype.updateRow = function updateRow(where_clause, set_fields, is_upsert, is_multi){
            var self = this;

            return new Promise(function(resolve, reject){
                getClient(server, pools, function(err, client){
                    if(err){
                        reject(err);
                        return;
                    }

                    client.collection(self.tableName).update(
                        where_clause,
                        set_fields,{ upsert: is_upsert, multi: is_multi },function(err, output){
                            if (err) {
                                reject(err);
                                return;
                            }
                            resolve(output);
                            return;
                    });
                });
            });
        };

        Model.prototype.findAndModifyRow = function findAndModifyRow(
            query, sort, remove, update, new_data, fields, upsert
            ){
            var self = this;

            return new Promise(function(resolve, reject){
               getclient(server, pools, function(err, client){
                   if(err){
                       reject(err);
                       return;
                   }
                   client.collection(self.tableName).findAndModifyRow(
                       {query: query},
                       {sort: sort},
                       {remove: remove},
                       {update: update},
                       {new: new_data},
                       {fields: fields},
                       {upsert: upsert}, function(err, output){
                           if(err){}
                       });

               });
            });

        };

        return Model;
    }

    return {
        extend: extend

    };
}

module.exports.initialize = initialize;

<|endoftext|>


<commit_before>
/*jslint node: true */
'use strict';

var dotenv  = require ( 'dotenv'   ).config(),
    Promise = require ( 'bluebird' ),
    chalk   = require ( 'chalk'    ),
    Redis   = require ( 'ioredis'  );

// ////////////////////////////////////////////////////////////////////////////
//
// common requirements,

var constant_server_restapi = require ( '../common/constant_server_restapi' );

// ////////////////////////////////////////////////////////////////////////////
//
// message relay, real-time framework for work with sockets
//
// using primus as an abstration around the real-time framework in use ( uws )

module.exports = function ( )
{
    var vm = this || {};

    vm._service_name = 'message_relay';

    vm.api =
    {
        ctor         : ctor,

        service_name : service_name
    };

    function ctor ( central_relay, storage_agent, restapi_agent )
    {
        return new Promise ( function ( resolve, reject )
        {
            var retval = false;

            // ////////////////////////////////////////////////////////////////
            //
            // framework resources

            vm.central_relay = central_relay;
            vm.storage_agent = storage_agent;
            vm.restapi_agent = restapi_agent;

            // ////////////////////////////////////////////////////////////////
            //
            // instance setup

            service_init ( ).then (

                function ( value )
                {
                },
                function ( error )
                {
                    throw ( error )
                }

            ).catch (

                function ( ex )
                {
                    console.log ( chalk.green ( '!!! ERROR : Unable to load -', vm._service_name ) );
                }

            ).finally (

                function ( )
                {

                    // ////////////////////////////////////////////////////////////////
                    //
                    // subscriptions

                    vm.central_relay.subscribe ( constant_server_restapi.restapi_listening,
                                                 on_central_relay_restapi_listening );

                    // ////////////////////////////////////////////////////////////////

                    console.log ( chalk.green ( 'on the line :', service_name ( ) ) );

                    retval = true;

                    resolve ( retval );

                }

            );

        } );

    }

    function service_name ( )
    {
        return vm._service_name;
    }

    function service_init ( )
    {
        return new Promise ( function ( resolve, reject )
        {
            vm.redis = new Redis (
            {
                port        : process.env.RD_SERVER_PORT,   // Redis port
                host        : process.env.RD_SERVER_HOST,   // Redis host
                family      : process.env.RD_SERVER_FAMILY, // 4 (IPv4) or 6 (IPv6)
                password    : process.env.RD_SERVER_AUTH,
                db          : process.env.RD_SERVER_DATA,

            } );

            resolve ( vm.redis );

        } );

    }

    function on_central_relay_restapi_listening ( data, envelope )
    {
        console.log ( chalk.green ( 'starting message agent' ) );

        var http_server = vm.restapi_agent.http_server_get ( );

    }

    return vm.api;
};
<commit_msg>- restapi server message agaent real-time socket server online<commit_after>
/*jslint node: true */
'use strict';

var dotenv          = require ( 'dotenv'        ).config(),
    _               = require ( 'lodash'        ),
    Promise         = require ( 'bluebird'      ),
    chalk           = require ( 'chalk'         ),
    Redis           = require ( 'ioredis'       ),
    Primus          = require ( 'primus'        ),
    Metroplex       = require ( 'metroplex'     ),
    OmegaSupreme    = require ( 'omega-supreme' ),
    PrimusEmit      = require ( 'primus-emit'   );

// ////////////////////////////////////////////////////////////////////////////
//
// common requirements,

var constant_server_restapi = require ( '../common/constant_server_restapi' );

// ////////////////////////////////////////////////////////////////////////////
//
// message relay, real-time framework for work with sockets
//
// using primus as an abstration around the real-time framework in use ( uws )
// ref https://remysharp.com/2014/11/10/muddling-my-way-through-real-time

module.exports = function ( )
{
    var vm = this || {};

    vm._service_name = 'message_agent';

    vm.api =
    {
        ctor         : ctor,

        service_name : service_name
    };

    vm.redis;
    vm.primus_options;
    vm.primus;

    function ctor ( central_relay, storage_agent, restapi_agent )
    {
        return new Promise ( function ( resolve, reject )
        {
            var retval = false;

            // ////////////////////////////////////////////////////////////////
            //
            // framework resources

            vm.central_relay = central_relay;
            vm.storage_agent = storage_agent;
            vm.restapi_agent = restapi_agent;

            // ////////////////////////////////////////////////////////////////
            //
            // instance setup

            service_init ( ).then (

                function ( value )
                {
                },
                function ( error )
                {
                    throw ( error )
                }

            ).catch (

                function ( ex )
                {
                    console.log ( chalk.green ( '!!! ERROR : Unable to load -', vm._service_name ) );
                }

            ).finally (

                function ( )
                {

                    // ////////////////////////////////////////////////////////////////
                    //
                    // subscriptions

                    vm.central_relay.subscribe ( constant_server_restapi.restapi_listening,
                                                 on_central_relay_restapi_listening );

                    // ////////////////////////////////////////////////////////////////

                    console.log ( chalk.green ( 'on the line :', service_name ( ) ) );

                    retval = true;

                    resolve ( retval );

                }

            );

        } );

    }

    function service_name ( )
    {
        return vm._service_name;
    }

    function service_init ( )
    {
        return new Promise ( function ( resolve, reject )
        {
            if ( 'localhost' === process.env.RD_SERVER_HOST )
            {
                vm.redis = new Redis (
                {
                    port        : process.env.RD_SERVER_PORT,   // Redis port
                    host        : process.env.RD_SERVER_HOST,   // Redis host
                    family      : process.env.RD_SERVER_FAMILY, // 4 (IPv4) or 6 (IPv6)
                    db          : process.env.RD_SERVER_DATA,

                } );

            } else
            {
                vm.redis = new Redis (
                {
                    port        : process.env.RD_SERVER_PORT,   // Redis port
                    host        : process.env.RD_SERVER_HOST,   // Redis host
                    family      : process.env.RD_SERVER_FAMILY, // 4 (IPv4) or 6 (IPv6)
                    password    : process.env.RD_SERVER_AUTH,
                    db          : process.env.RD_SERVER_DATA,

                } );

            }

            vm.redis.on ( "error", function ( err )
            {
                console.log ( "!!! Redis Error -", err );

            } );

            resolve ( vm.redis );

        } );

    }

    function on_central_relay_restapi_listening ( data, envelope )
    {
        console.log ( chalk.green ( 'starting message agent' ) );

        vm.http_server = vm.restapi_agent.http_server_get ( );

        vm.primus_options =
        {
            transformer : 'uws',
            redis       : vm.redis,
            namespace   : 'metroplex'
        };

        vm.primus = new Primus ( vm.http_server, vm.primus_options );

        // add the Primus middleware ( after instantiation )

        vm.primus.plugin ( 'metroplex',        Metroplex    );
        vm.primus.plugin ( 'omega-supreme',    OmegaSupreme );
        vm.primus.plugin ( 'emit',             PrimusEmit   );

        // query the registered servers

        vm.primus.metroplex.servers ( function ( err, servers )
        {
            console.log ( 'other servers: %d', servers.length, servers );

        } );

        vm.primus.save ( __dirname + '/../../../common/source/mortis_primus.js' );

        // when we get a connection...
        vm.primus.on ( 'connection', function ( spark )
        {
            // the inbound socket is referred to as a "spark"

            console.log ( 'whoa.. they do exist -', spark.id );

            // respond to ping events with a pong

            spark.on ( 'ping', function ()
            {
                spark.emit ( 'pong' );

            } );

        } );

        console.log ( chalk.green ( 'message agent started' ) );

    }

    return vm.api;
};
<|endoftext|>


<commit_before><commit_msg>optimize: return new dom-like element in toDOM<commit_after><|endoftext|>


<commit_before>'use strict'; //eslint-disable-line
const clc = require('cli-color');
const GitHubApi = require('github');
const print = require('./print');
let debug = false;
let limit = 0; // No limit
const github = new GitHubApi({
  version: '3.0.0'
});

/**
 * Toggles debug mode.
 * @param {Boolean} mode Sets the debug state
 */
function setDebugMode(mode) {
  debug = mode;
}

/**
 * Sets the max. number of repositories to query for open PRs.
 * @param {Integer} repoLimit Number of repos to query
 */
function setRepoLimit(repoLimit) {
  limit = repoLimit;
}

/**
 * Initialize and authenticate the github API with,
 * @param  {Object} auth Credentials containing an auth token
 * @return {Promise}     Only resolves to continue the async flow
 */
function authenticate(auth) {
  return new Promise((resolve) => {
    github.authenticate(auth);
    resolve();
  });
}

/**
 * Retrieves a list of repositories (All or limited).
 * @param  {Object}  auth         Credentials containing an auth token
 * @param  {Integer} repoLimit    Max. number of repos to query for PRs
 * @param  {Boolean} debugEnabled Set the debug state
 * @return {Promise}              Array of repositories
 */
function getRepos(auth, repoLimit, debugEnabled) {
  setRepoLimit(repoLimit);
  setDebugMode(debugEnabled);
  print(`Fetching repos (${limit ? 'First ' + limit : 'No limit'})`, debug);
  return authenticate(auth)
  .then(() => {
    return new Promise((resolve, reject) => {
      github.repos.getAll({
        sort: 'pushed',
        per_page: limit || 100 //eslint-disable-line
      }, (err, repos) => {
        if (err) {
          return reject(err);
        }
        return resolve(repos);
      });
    });
  });
}

/**
 * Fetch open pull requests for a single repository
 * @param  {Object}  repo Repository metadata
 * @return {Promise}      Resolves to a list of pull requests
 */
function getPRsForRepo(repo) {
  print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug);
  return new Promise((resolve, reject) => {
    github.pullRequests.getAll({
      user: repo.owner.login,
      repo: repo.name,
      state: 'open'
    }, (err, prs) => {
      if (err) {
        return reject(err);
      }
      return resolve(prs.filter((pr) => {
        return pr && pr.head;
      }));
    });
  });
}

/**
 * Fetch a list of labels for a single pull-request
 * @param  {Object}  pr Pull-request metadata
 * @return {Promise}    Resolves to an array of labels
 */
function populateLabelsForPR(pr) {
  print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
  return new Promise((resolve) => {
    github.issues.getIssueLabels({
      user: pr.base.user.login,
      repo: pr.base.repo.name,
      number: pr.number
    }, function (err, labels) {
      if (err && debug) {
        print(['Error fetching labels for PR ', clc.red.bold`${pr.base.user.login}/${pr.base.repo.name}#${pr.number}`], debug);
      }
      if (labels && labels.length > 0) {
        pr.labels = labels.map((label) => {
          return {
            name: label.name,
            color: label.color
          };
        });
      }
      return resolve(pr);
    });
  });
}

/**
 * Fetch labels for a list of pull-requests
 * @param  {Array}  repos List of pull-requests
 * @return {Promise}      Resolves to an array of PRs containing labels
 */
function getLabels(prs) {
  return Promise.all(prs.reduce((flattenedPRs, pr) => {
    if (pr) {
      return flattenedPRs.concat(pr);
    }
  }, []).map(populateLabelsForPR));
}

/**
 * Create a new error handler of a given type
 * @param  {String}   type The type of error to display
 * @return {Function}      Error logger
 */
function handleError(type) {
  return (err) => {
    console.error('ERROR:', type);
    console.error(err);
  };
}

/**
 * Reduce a patch down to just changed lines
 * @param  {String} patch The complete patch with surrounding context
 * @return {Object}       Stats about the changed lines
 */
function analyzePatch(patch) {
  const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => {
    if (currentLine.match(/^[-+]/)) {
      return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, ''));
    }
    return reducedPatch;
  }, []);
  return {
    lines: patchLines.length,
    chars: patchLines.join('').length
  };
}

/**
 * Refine a complete diff down to its useful information
 * @param  {Object} diff Too much information about a diff
 * @return {Object}      Just enough information about a diff
 */
function extractDiffData(diff) {
  print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug);
  return {
    user: diff.user,
    repo: diff.repo,
    title: diff.title,
    number: diff.number,
    link: diff.link,
    createdAt: diff.createdAt,
    updatedAt: diff.updatedAt,
    labels: diff.labels,
    aheadBy: diff.ahead_by,
    behindBy: diff.behind_by,
    status: diff.status,
    totalCommits: diff.total_commits,
    author: {
      login: diff.merge_base_commit.author.login,
      avatarUrl: diff.merge_base_commit.author.avatar_url,
    },
    files: diff.files.map((file) => {
      return {
        filename: file.filename,
        status: file.status,
        additions: file.additions,
        deletions: file.deletions,
        changes: file.changes,
        patch: analyzePatch(file.patch || '')
      };
    })
  };
}

/**
 * Fetch the diff for a single pull-request
 * @param  {Object}  pr Pull-request metadata
 * @return {Promise}    Resolves to an array of labels
 */
function getDiffForPR(pr) {
  print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
  return new Promise((resolve) => {
    github.repos.compareCommits({
      user: pr.head.user.login,
      repo: pr.head.repo.name,
      head: pr.head.ref,
      base: pr.base.ref
    }, (err, diff) => {
      if (err && debug) {
        print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug);
      }
      diff.user = pr.head.user.login;
      diff.repo = pr.head.repo.name;
      diff.title = pr.title;
      diff.number = pr.number;
      diff.link = pr._links.html.href;
      diff.createdAt = pr.created_at;
      diff.createdAt = pr.updated_at;
      diff.labels = pr.labels;
      return resolve(extractDiffData(diff));
    });
  });
}

/**
 * Fetch diffs for a list of pull-requests
 * @param  {Array}  repos List of pull-requests
 * @return {Promise}      Resolves to an array of PRs containing diff infomation
 */
function getDiffs(prs) {
  print('Fetching diffs', debug);
  return Promise.all(prs.reduce((flattenedPRs, pr) => {
    if (pr) {
      return flattenedPRs.concat(pr);
    }
  }, []).map(getDiffForPR));
}

/**
 * Get a list of all open pull requests.
 * @param  {Object}  auth         Credentials containing an auth token
 * @param  {Object}  repo         The repo from which to get the Open PRs
 * @param  {Boolean} debugEnabled Set the debug state
 * @return {Promise}              Resolves to a list of all open pull-requests
 */
function getOpenPRs(auth, repo, debugEnabled) {
  setDebugMode(debugEnabled);
  return authenticate(auth)
    .then(function () {
      return getPRsForRepo(repo)
        .then(getLabels, handleError('getPRs'))
        .then(getDiffs, handleError('getLabels'));
    }, handleError('authenticate'));
}

module.exports = {
  setDebug: setDebugMode,
  setLimit: setRepoLimit,
  getOpenPRs,
  getRepos
};
<commit_msg>Fixed api interface:<commit_after>'use strict'; //eslint-disable-line
const clc = require('cli-color');
const GitHubApi = require('github');
const print = require('./print');
let debug = false;
let limit = 0; // No limit
const github = new GitHubApi({
  version: '3.0.0'
});

/**
 * Toggles debug mode.
 * @param {Boolean} mode Sets the debug state
 */
function setDebugMode(mode) {
  debug = mode;
}

/**
 * Sets the max. number of repositories to query for open PRs.
 * @param {Integer} repoLimit Number of repos to query
 */
function setRepoLimit(repoLimit) {
  limit = repoLimit;
}

/**
 * Initialize and authenticate the github API with,
 * @param  {Object} auth Credentials containing an auth token
 * @return {Promise}     Only resolves to continue the async flow
 */
function authenticate(auth) {
  return new Promise((resolve) => {
    github.authenticate(auth);
    resolve();
  });
}

/**
 * Retrieves a list of repositories (All or limited).
 * @param  {Object}  auth         Credentials containing an auth token
 * @param  {Integer} repoLimit    Max. number of repos to query for PRs
 * @param  {Boolean} debugEnabled Set the debug state
 * @return {Promise}              Array of repositories
 */
function getRepos(auth, repoLimit, debugEnabled) {
  setRepoLimit(repoLimit);
  setDebugMode(debugEnabled);
  print(`Fetching repos (${limit ? 'First ' + limit : 'No limit'})`, debug);
  return authenticate(auth)
  .then(() => {
    return new Promise((resolve, reject) => {
      github.repos.getAll({
        sort: 'pushed',
        per_page: limit || 100 //eslint-disable-line
      }, (err, repos) => {
        if (err) {
          return reject(err);
        }
        return resolve(repos);
      });
    });
  });
}

/**
 * Fetch open pull requests for a single repository
 * @param  {Object}  repo Repository metadata
 * @return {Promise}      Resolves to a list of pull requests
 */
function getPRsForRepo(repo) {
  print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug);
  return new Promise((resolve, reject) => {
    github.pullRequests.getAll({
      user: repo.owner.login,
      repo: repo.name,
      state: 'open'
    }, (err, prs) => {
      if (err) {
        return reject(err);
      }
      return resolve(prs.filter((pr) => {
        return pr && pr.head;
      }));
    });
  });
}

/**
 * Fetch a list of labels for a single pull-request
 * @param  {Object}  pr Pull-request metadata
 * @return {Promise}    Resolves to an array of labels
 */
function populateLabelsForPR(pr) {
  print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
  return new Promise((resolve) => {
    github.issues.getIssueLabels({
      user: pr.base.user.login,
      repo: pr.base.repo.name,
      number: pr.number
    }, function (err, labels) {
      if (err && debug) {
        print(['Error fetching labels for PR ', clc.red.bold`${pr.base.user.login}/${pr.base.repo.name}#${pr.number}`], debug);
      }
      if (labels && labels.length > 0) {
        pr.labels = labels.map((label) => {
          return {
            name: label.name,
            color: label.color
          };
        });
      }
      return resolve(pr);
    });
  });
}

/**
 * Fetch labels for a list of pull-requests
 * @param  {Array}  repos List of pull-requests
 * @return {Promise}      Resolves to an array of PRs containing labels
 */
function getLabels(prs) {
  return Promise.all(prs.reduce((flattenedPRs, pr) => {
    if (pr) {
      return flattenedPRs.concat(pr);
    }
  }, []).map(populateLabelsForPR));
}

/**
 * Create a new error handler of a given type
 * @param  {String}   type The type of error to display
 * @return {Function}      Error logger
 */
function handleError(type) {
  return (err) => {
    console.error('ERROR:', type);
    console.error(err);
  };
}

/**
 * Reduce a patch down to just changed lines
 * @param  {String} patch The complete patch with surrounding context
 * @return {Object}       Stats about the changed lines
 */
function analyzePatch(patch) {
  const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => {
    if (currentLine.match(/^[-+]/)) {
      return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, ''));
    }
    return reducedPatch;
  }, []);
  return {
    lines: patchLines.length,
    chars: patchLines.join('').length
  };
}

/**
 * Refine a complete diff down to its useful information
 * @param  {Object} diff Too much information about a diff
 * @return {Object}      Just enough information about a diff
 */
function extractDiffData(diff) {
  print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug);
  return {
    user: diff.user,
    repo: diff.repo,
    title: diff.title,
    number: diff.number,
    link: diff.link,
    createdAt: diff.createdAt,
    updatedAt: diff.updatedAt,
    labels: diff.labels,
    aheadBy: diff.ahead_by,
    behindBy: diff.behind_by,
    status: diff.status,
    totalCommits: diff.total_commits,
    author: {
      login: diff.merge_base_commit.author.login,
      avatarUrl: diff.merge_base_commit.author.avatar_url,
    },
    files: diff.files.map((file) => {
      return {
        filename: file.filename,
        status: file.status,
        additions: file.additions,
        deletions: file.deletions,
        changes: file.changes,
        patch: analyzePatch(file.patch || '')
      };
    })
  };
}

/**
 * Fetch the diff for a single pull-request
 * @param  {Object}  pr Pull-request metadata
 * @return {Promise}    Resolves to an array of labels
 */
function getDiffForPR(pr) {
  print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
  return new Promise((resolve) => {
    github.repos.compareCommits({
      user: pr.head.user.login,
      repo: pr.head.repo.name,
      head: pr.head.ref,
      base: pr.base.ref
    }, (err, diff) => {
      if (err && debug) {
        print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug);
      }
      diff.user = pr.head.user.login;
      diff.repo = pr.head.repo.name;
      diff.title = pr.title;
      diff.number = pr.number;
      diff.link = pr._links.html.href;
      diff.createdAt = pr.created_at;
      diff.createdAt = pr.updated_at;
      diff.labels = pr.labels;
      return resolve(extractDiffData(diff));
    });
  });
}

/**
 * Fetch diffs for a list of pull-requests
 * @param  {Array}  repos List of pull-requests
 * @return {Promise}      Resolves to an array of PRs containing diff infomation
 */
function getDiffs(prs) {
  print('Fetching diffs', debug);
  return Promise.all(prs.reduce((flattenedPRs, pr) => {
    if (pr) {
      return flattenedPRs.concat(pr);
    }
  }, []).map(getDiffForPR));
}

/**
 * Get a list of all open pull requests.
 * @param  {Object}  auth         Credentials containing an auth token
 * @param  {Object}  repo         The repo from which to get the Open PRs
 * @param  {Boolean} debugEnabled Set the debug state
 * @return {Promise}              Resolves to a list of all open pull-requests
 */
function getOpenPRs(auth, repo, debugEnabled) {
  setDebugMode(debugEnabled);
  return authenticate(auth)
    .then(function () {
      return getPRsForRepo(repo)
        .then(getLabels, handleError('getPRs'))
        .then(getDiffs, handleError('getLabels'));
    }, handleError('authenticate'));
}

module.exports = {
  setDebugMode,
  setRepoLimit,
  getOpenPRs,
  getRepos
};
<|endoftext|>


<commit_before>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var extend         = require('extend');
var requestFactory = require('../../lib/requestwrapper');
var isStream       = require('isstream');

function DocumentConversion(options) {
  // Default URL
  var serviceDefaults = {
    url: 'https://gateway.watsonplatform.net/document-conversion-experimental/api'
  };

  // Replace default options with user provided
  this._options = extend(serviceDefaults, options);
}

DocumentConversion.prototype.conversion_target = {
  ANSWER_UNITS: 'ANSWER_UNITS',
  NORMALIZED_HTML: 'NORMALIZED_HTML',
  NORMALIZED_TEXT: 'NORMALIZED_TEXT'
};

DocumentConversion.prototype.job_status = {
  SUBMITTED: 'SUBMITTED',
  IN_PROGRESS: 'IN_PROGRESS',
  COMPLETE: 'COMPLETE',
  CANCELLED: 'CANCELLED'
};

/**
 * Gets a list of existing batches.
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {String} [params.name] filter the results to only the one batch with the given name. If multiple batches share the same name, this will only return the first one.
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 */
DocumentConversion.prototype.getBatches = function(params, callback) {
  params = params || {};
  if (params.since && params.since instanceof Date) {
    params.since = params.since.toISOString();
  }
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Creates a new batch
 *
 * @param {String} [params.name] optional name for the batch. Should be unique
 * @param {Array<Object>} [params.properties] optional list of properties. Each one should be an object with the keys "name" and "value" and string values for each key.
 */
DocumentConversion.prototype.createBatch = function(params, callback) {
  params = params || {};

  if (params.name === '') {
    callback(new Error('Batch name may not be blank'));
    return;
  }

  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/batches',
      body: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets an existing batch
 *
 * @param {String} batch_id
 */
DocumentConversion.prototype.getBatch = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches/{batch_id}',
      qs: params,
      path: params,
      json: true
    },
    requiredParams:['batch_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Updates an existing batch
 * @param {String} batch_id the batch identifier
 *
 */
DocumentConversion.prototype.updateBatch = function(params, callback) {

  if (!params.batch_id) {
    callback(new Error('batch_id is required'));
    return;
  }

  var id = params.batch_id;
  var pcopy = extend ({}, params);
  delete pcopy.batch_id;

  var parameters = {
    options: {
      method: 'PUT',
      url: '/v1/batches/' + id,
      body: pcopy,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets a list of existing documents in the batch
 *
 * @param {String} batch_id the batch identifier
 */
DocumentConversion.prototype.getBatchDocuments = function(params, callback) {

  if (!params.batch_id) {
    callback(new Error('batch_id is required'));
    return;
  }

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches/' + params.batch_id + '/documents',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

function fixupContentType(params) {
  if (params.file && params.file.path && /.html?$/.test(params.file.path)) {
    params.file = {
      value: params.file,
      options: {
        contentType: 'text/html; charset=utf-8'
      }
    };
  }
}

/**
 * One-off convert an attached document OR convert a previously uploaded document by ID
 *
 * To convert a previously uploaded document, set params.document_id
 *
 * @param  {Object} params.conversion_target Must be set to one of ['ANSWER_UNITS', 'NORMALIZED_HTML', 'NORMALIZED_TEXT']
 * @param  {Object} [params.document_id] Id of previously uploaded document to convert
 * @param  {ReadableStream} [params.file] The document file to convert.
 */
DocumentConversion.prototype.convert = function(params, callback) {
  params = params || {};

  if (!params.conversion_target || !DocumentConversion.prototype.conversion_target[params.conversion_target]) {
    callback(new Error('Missing required parameter: params.conversion_target'));
    return;
  }

  if (!params.file && !params.document_id) {
    callback(new Error('Missing required parameter: either params.file or params.document_id must be specified'));
    return;
  }

  if (params.file && !isStream(params.file) && !params.file.value) {
    callback(new Error('file is not a standard Node.js Stream'));
    return;
  }

  fixupContentType(params);

  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/convert_document',
      formData: params,
      json: true
    },
    defaultOptions: this._options
  };

  return requestFactory(parameters, callback);
};

/**
 * Upload a document for later conversion
 *
 * @param  {ReadableStream} params.file The document file to convert.
 */
DocumentConversion.prototype.uploadDocument = function(params, callback) {
  params = params || {};

  if (!params.file) {
    callback(new Error('Missing required parameter: file'));
    return;
  }

  if (!isStream(params.file) && !params.file.value) {
    callback(new Error('file is not a standard Node.js Stream'));
    return;
  }

  fixupContentType(params);

  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/documents',
      formData: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Retrieve a list of all previously uploaded documents
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {String} [params.name] filter the results to only documents with the given name.
 */
DocumentConversion.prototype.getDocuments = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/documents',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Retrieve a previously uploaded document
 *
 * @param  {String} params.id The ID returned when the document was uploaded
 */
DocumentConversion.prototype.getDocument = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/documents/{id}',
      json: true
    },
    requiredParams:['id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Add a previously uploaded document to a batch
 *
 * @param  {String} params.id The ID returned when the document was uploaded
 */
DocumentConversion.prototype.addDocumentToBatch = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'PUT',
      url: '/v1/batches/{batch_id}/documents/{document_id}',
      json: true
    },
    requiredParams:['batch_id','document_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Get the list of documents in a batch
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 */
DocumentConversion.prototype.getBatchDocuments = function(params, callback) {
  params = params || {};

  if (params.since && params.since instanceof Date) {
    params.since = params.since.toISOString();
  }

  var parameters = {
    options: {
      method: 'PUT',
      url: '/v1/batches/{batch_id}/documents',
      qs: params,
      json: true
    },
    requiredParams:['batch_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Get details about a document in a batch
 * @param params.batch_id
 * @param params.document_id
 * @param callback
 * @returns {*}
 */
DocumentConversion.prototype.getBatchDocument = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches/{batch_id}/documents/{document_id}',
      path: params,
      json: true
    },
    requiredParams:['batch_id', 'document_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Creates a job to convert a batch of documents
 *
 * @param params.name
 * @param params.batch_id
 * @param params.conversion_target
 * @param callback
 */
DocumentConversion.prototype.createJob = function(params, callback) {
  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/jobs',
      body: params,
      json: true
    },
    requiredParams:['name', 'batch_id', 'conversion_target'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets a list of existing batches.
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {String} [params.name] filter the results to only the one batch with the given name. If multiple batches share the same name, this will only return the first one.
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 * @param {string} [params.status]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 */
DocumentConversion.prototype.getJobs = function(params, callback) {
  params = params || {};

  if (params.since && params.since instanceof Date) {
    params.since = params.since.toISOString();
  }

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/jobs',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets information about a job
 *
 * @param {String} params.job_id
 */
DocumentConversion.prototype.getJob = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/jobs/{job_id}',
      path: params,
      json: true
    },
    requiredParams:['job_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets the job processing log
 *
 * @param {String} params.job_id
 */
DocumentConversion.prototype.getJobLog = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/jobs/{job_id}/log',
      path: params
    },
    requiredParams:['job_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets a collection of generated outputs
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 * @param {String} [params.job_id] return only results fro the specified job
 * @param {String} [params.media_type] filter the results to only the given media_type
 */
DocumentConversion.prototype.getOutputs = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/output',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets the content of the output
 *
 * @param {String} params.output_id
 */
DocumentConversion.prototype.getOutput = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/output/{output_id}',
      path: params,
      json: true
    },
    requiredParams:['output_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

module.exports = DocumentConversion;
<commit_msg>added javadoc and fix /convert<commit_after>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var extend         = require('extend');
var requestFactory = require('../../lib/requestwrapper');
var isStream       = require('isstream');
var pick           = require('object.pick');
var omit           = require('object.omit');

function DocumentConversion(options) {
  // Default URL
  var serviceDefaults = {
    url: 'https://gateway.watsonplatform.net/document-conversion-experimental/api'
  };

  // Replace default options with user provided
  this._options = extend(serviceDefaults, options);
}

DocumentConversion.prototype.conversion_target = {
  ANSWER_UNITS: 'ANSWER_UNITS',
  NORMALIZED_HTML: 'NORMALIZED_HTML',
  NORMALIZED_TEXT: 'NORMALIZED_TEXT'
};

DocumentConversion.prototype.job_status = {
  SUBMITTED: 'SUBMITTED',
  IN_PROGRESS: 'IN_PROGRESS',
  COMPLETE: 'COMPLETE',
  CANCELLED: 'CANCELLED'
};

/**
 * Gets a list of existing batches.
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {String} [params.name] filter the results to only the one batch with the given name. If multiple batches share the same name, this will only return the first one.
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 */
DocumentConversion.prototype.getBatches = function(params, callback) {
  params = params || {};
  if (params.since && params.since instanceof Date) {
    params.since = params.since.toISOString();
  }
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Creates a new batch
 *
 * @param {String} [params.name] optional name for the batch. Should be unique
 * @param {Array<Object>} [params.properties] optional list of properties. Each one should be an object with the keys "name" and "value" and string values for each key.
 */
DocumentConversion.prototype.createBatch = function(params, callback) {
  params = params || {};

  if (params.name === '') {
    callback(new Error('Batch name may not be blank'));
    return;
  }

  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/batches',
      body: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets an existing batch
 *
 * @param {String} batch_id
 */
DocumentConversion.prototype.getBatch = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches/{batch_id}',
      path: params,
      json: true
    },
    requiredParams:['batch_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Updates an existing batch
 * @param {String} batch_id the batch identifier
 *
 */
DocumentConversion.prototype.updateBatch = function(params, callback) {
  var parameters = {
    options: {
      method: 'PUT',
      url: '/v1/batches/{batch_id}',
      body: omit(params,['batch_id']),
      path: pick(params,['batch_id']),
      json: true
    },
    requiredParams:['batch_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets a list of existing documents in the batch
 *
 * @param {String} batch_id the batch identifier
 */
DocumentConversion.prototype.getBatchDocuments = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches/{batch_id}/documents',
      qs: omit(params,['batch_id']),
      path: pick(params,['batch_id']),
      json: true
    },
    requiredParams: ['batch_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

function fixupContentType(params) {
  if (params.file && params.file.path && /.html?$/.test(params.file.path)) {
    params.file = {
      value: params.file,
      options: {
        contentType: 'text/html; charset=utf-8'
      }
    };
  }
}

/**
 * One-off convert an attached document OR convert a previously uploaded document by ID
 *
 * To convert a previously uploaded document, set params.document_id
 *
 * @param  {Object} params.conversion_target Must be set to one of ['ANSWER_UNITS', 'NORMALIZED_HTML', 'NORMALIZED_TEXT']
 * @param  {Object} [params.document_id] Id of previously uploaded document to convert
 * @param  {ReadableStream} [params.file] The document file to convert.
 */
DocumentConversion.prototype.convert = function(params, callback) {
  params = params || {};
  if (!params.conversion_target || !DocumentConversion.prototype.conversion_target[params.conversion_target]) {
    var keys = Object.keys(DocumentConversion.prototype.conversion_target);
    var values = keys.map(function(v) { return DocumentConversion.prototype.conversion_target[v]; });

    callback(new Error('Missing required parameter: conversion_target. Possible values are: ' + values.join(', ')));
    return;
  }

  if (!params.file && !params.document_id) {
    callback(new Error('Missing required parameter: either params.file or params.document_id must be specified'));
    return;
  }

  if (params.file && !isStream(params.file) && !params.file.value) {
    callback(new Error('file is not a standard Node.js Stream'));
    return;
  }

  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/convert_document',
      json: true
    },
    defaultOptions: this._options
  };

  // send the parameters in the body or as formData depending on the request
  if (params.file) {
  fixupContentType(params);
    parameters.options.formData = params;
  } else {
    parameters.options.body = params;
  }

  return requestFactory(parameters, callback);
};

/**
 * Upload a document for later conversion
 *
 * @param  {ReadableStream} params.file The document file to convert.
 */
DocumentConversion.prototype.uploadDocument = function(params, callback) {
  params = params || {};

  if (!params.file) {
    callback(new Error('Missing required parameter: file'));
    return;
  }

  if (!isStream(params.file) && !params.file.value) {
    callback(new Error('file is not a standard Node.js Stream'));
    return;
  }

  fixupContentType(params);

  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/documents',
      formData: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Retrieve a list of all previously uploaded documents
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {String} [params.name] filter the results to only documents with the given name.
 */
DocumentConversion.prototype.getDocuments = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/documents',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Retrieve a previously uploaded document
 *
 * @param  {String} params.id The ID returned when the document was uploaded
 */
DocumentConversion.prototype.getDocument = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/documents/{id}',
      json: true,
      path: params
    },
    requiredParams:['id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Add a previously uploaded document to a batch
 *
 * @param  {String} params.id The ID returned when the document was uploaded
 */
DocumentConversion.prototype.addDocumentToBatch = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'PUT',
      url: '/v1/batches/{batch_id}/documents/{document_id}',
      json: true
    },
    requiredParams:['batch_id','document_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Get the list of documents in a batch
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 */
DocumentConversion.prototype.getBatchDocuments = function(params, callback) {
  params = params || {};

  if (params.since && params.since instanceof Date) {
    params.since = params.since.toISOString();
  }

  var parameters = {
    options: {
      method: 'PUT',
      url: '/v1/batches/{batch_id}/documents',
      qs: params,
      json: true
    },
    requiredParams:['batch_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Get details about a document in a batch
 * @param params.batch_id
 * @param params.document_id
 * @param callback
 * @returns {*}
 */
DocumentConversion.prototype.getBatchDocument = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/batches/{batch_id}/documents/{document_id}',
      path: params,
      json: true
    },
    requiredParams:['batch_id', 'document_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Creates a job to convert a batch of documents
 *
 * @param params.name
 * @param params.batch_id
 * @param params.conversion_target
 * @param callback
 */
DocumentConversion.prototype.createJob = function(params, callback) {
  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/jobs',
      body: params,
      json: true
    },
    requiredParams:['name', 'batch_id', 'conversion_target'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets a list of existing batches.
 *
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {String} [params.name] filter the results to only the one batch with the given name. If multiple batches share the same name, this will only return the first one.
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 * @param {string} [params.status]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 */
DocumentConversion.prototype.getJobs = function(params, callback) {
  params = params || {};

  if (params.since && params.since instanceof Date) {
    params.since = params.since.toISOString();
  }

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/jobs',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets information about a job
 *
 * @param {String} params.job_id
 */
DocumentConversion.prototype.getJob = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/jobs/{job_id}',
      path: params,
      json: true
    },
    requiredParams:['job_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets the job processing log
 *
 * @param {String} params.job_id
 */
DocumentConversion.prototype.getJobLog = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/jobs/{job_id}/log',
      path: params
    },
    requiredParams:['job_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets a collection of generated outputs
 * todo: make working with tokens / pagination easier
 *
 * @param {Number} [params.limit] limit the number of results returned
 * @param {String} [params.token] for pagination (see the `next` link in the `links` section of the response)
 * @param {Date|string} [params.since]: filter the results to only those newer than this date. Date object or ISO 8601-formatted string
 * @param {String} [params.job_id] return only results fro the specified job
 * @param {String} [params.media_type] filter the results to only the given media_type
 */
DocumentConversion.prototype.getOutputs = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/output',
      qs: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Gets the content of the output
 *
 * @param {String} params.output_id
 */
DocumentConversion.prototype.getOutput = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/output/{output_id}',
      path: params,
      json: true
    },
    requiredParams:['output_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

module.exports = DocumentConversion;
<|endoftext|>


<commit_before>/**
 * @fileOverview Tooltip
 */
import React, { Component, PropTypes } from 'react';
import pureRender from '../util/PureRender';
import ReactDOMServer from 'react-dom/server';
import DefaultTooltipContent from './DefaultTooltipContent';
import { getStyleString } from '../util/DOMUtils';
import { isSsr } from '../util/ReactUtils';
import _ from 'lodash';

const propTypes = {
  content: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
  viewBox: PropTypes.shape({
    x: PropTypes.number,
    y: PropTypes.number,
    width: PropTypes.number,
    height: PropTypes.number,
  }),

  active: PropTypes.bool,
  separator: PropTypes.string,
  formatter: PropTypes.func,
  offset: PropTypes.number,

  itemStyle: PropTypes.object,
  labelStyle: PropTypes.object,
  wrapperStyle: PropTypes.object,
  cursor: PropTypes.oneOfType([PropTypes.bool, PropTypes.element, PropTypes.object]),

  coordinate: PropTypes.shape({
    x: PropTypes.number,
    y: PropTypes.number,
  }),

  label: PropTypes.any,
  payload: PropTypes.arrayOf(PropTypes.shape({
    name: PropTypes.any,
    value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    unit: PropTypes.any,
  })),
};

const defaultProps = {
  active: false,
  offset: 10,
  viewBox: { x1: 0, x2: 0, y1: 0, y2: 0 },
  coordinate: { x: 0, y: 0 },
  cursorStyle: {},
  separator: ' : ',
  wrapperStyle: {},
  itemStyle: {},
  labelStyle: {},
  cursor: true,
};

const getTooltipBBox = (wrapperStyle, contentItem) => {
  if (!isSsr()) {
    const contentHtml = ReactDOMServer.renderToStaticMarkup(contentItem);
    const style = { ...wrapperStyle, top: -20000, left: 0, display: 'block' };

    const wrapper = document.createElement('div');

    wrapper.setAttribute('style', getStyleString(style));
    wrapper.innerHTML = contentHtml;
    document.body.appendChild(wrapper);
    const box = wrapper.getBoundingClientRect();

    document.body.removeChild(wrapper);

    return box;
  }

  return null;
};

const renderContent = (content, props) => {
  if (React.isValidElement(content)) {
    return React.cloneElement(content, props);
  } else if (_.isFunction(content)) {
    return content(props);
  }

  return React.createElement(DefaultTooltipContent, props);
};

class Tooltip extends Component {
  static displayName = 'Tooltip';
  static propTypes = propTypes;
  static defaultProps = defaultProps;

  render() {
    const { payload } = this.props;
    if (!payload || !payload.length) {return null;}

    const { content, viewBox, coordinate, active, offset } = this.props;
    const outerStyle = {
      pointerEvents: 'none',
      display: active ? 'block' : 'none',
      position: 'absolute',
    };
    const contentItem = renderContent(content, this.props);
    const box = getTooltipBBox(outerStyle, contentItem);

    if (!box) { return null; }

    outerStyle.left = Math.max(
      coordinate.x + box.width + offset > (viewBox.x + viewBox.width) ?
      coordinate.x - box.width - offset :
      coordinate.x + offset, viewBox.x);
    outerStyle.top = Math.max(
      coordinate.y + box.height + offset > (viewBox.y + viewBox.height) ?
      coordinate.y - box.height - offset :
      coordinate.y + offset, viewBox.y);

    return (
      <div className="recharts-tooltip-wrapper" style={outerStyle}>
        {contentItem}
      </div>
    );
  }
}

export default Tooltip;
<commit_msg>feat(tooltip): add tooltip animation (#83)<commit_after>/**
 * @fileOverview Tooltip
 */
import React, { Component, PropTypes } from 'react';
import pureRender from '../util/PureRender';
import ReactDOMServer from 'react-dom/server';
import DefaultTooltipContent from './DefaultTooltipContent';
import { getStyleString } from '../util/DOMUtils';
import { isSsr } from '../util/ReactUtils';
import Animate from 'react-smooth';
import _ from 'lodash';

const propTypes = {
  content: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
  viewBox: PropTypes.shape({
    x: PropTypes.number,
    y: PropTypes.number,
    width: PropTypes.number,
    height: PropTypes.number,
  }),

  active: PropTypes.bool,
  separator: PropTypes.string,
  formatter: PropTypes.func,
  offset: PropTypes.number,

  itemStyle: PropTypes.object,
  labelStyle: PropTypes.object,
  wrapperStyle: PropTypes.object,
  cursor: PropTypes.oneOfType([PropTypes.bool, PropTypes.element, PropTypes.object]),

  coordinate: PropTypes.shape({
    x: PropTypes.number,
    y: PropTypes.number,
  }),

  label: PropTypes.any,
  payload: PropTypes.arrayOf(PropTypes.shape({
    name: PropTypes.any,
    value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    unit: PropTypes.any,
  })),

  isAnimationActive: PropTypes.bool,
  animationDuration: PropTypes.number,
  animationEasing: PropTypes.oneOf([
    'ease',
    'ease-in',
    'ease-out',
    'ease-in-out',
    'linear',
  ]),
};

const defaultProps = {
  active: false,
  offset: 10,
  viewBox: { x1: 0, x2: 0, y1: 0, y2: 0 },
  coordinate: { x: 0, y: 0 },
  cursorStyle: {},
  separator: ' : ',
  wrapperStyle: {},
  itemStyle: {},
  labelStyle: {},
  cursor: true,
  isAnimationActive: true,
  animationEasing: 'ease',
  animationDuration: 400,
};

const getTooltipBBox = (wrapperStyle, contentItem) => {
  if (!isSsr()) {
    const contentHtml = ReactDOMServer.renderToStaticMarkup(contentItem);
    const style = { ...wrapperStyle, top: -20000, left: 0, display: 'block' };

    const wrapper = document.createElement('div');

    wrapper.setAttribute('style', getStyleString(style));
    wrapper.innerHTML = contentHtml;
    document.body.appendChild(wrapper);
    const box = wrapper.getBoundingClientRect();

    document.body.removeChild(wrapper);

    return box;
  }

  return null;
};

const renderContent = (content, props) => {
  if (React.isValidElement(content)) {
    return React.cloneElement(content, props);
  } else if (_.isFunction(content)) {
    return content(props);
  }

  return React.createElement(DefaultTooltipContent, props);
};

class Tooltip extends Component {
  static displayName = 'Tooltip';
  static propTypes = propTypes;
  static defaultProps = defaultProps;

  render() {
    const { payload, isAnimationActive, animationDuration, animationEasing } = this.props;
    if (!payload || !payload.length) {return null;}

    const { content, viewBox, coordinate, active, offset } = this.props;
    const outerStyle = {
      pointerEvents: 'none',
      display: active ? 'block' : 'none',
      position: 'absolute',
      top: 0,
    };
    const contentItem = renderContent(content, this.props);
    const box = getTooltipBBox(outerStyle, contentItem);

    if (!box) { return null; }

    const translateX = Math.max(
      coordinate.x + box.width + offset > (viewBox.x + viewBox.width) ?
      coordinate.x - box.width - offset :
      coordinate.x + offset, viewBox.x);

    const translateY = Math.max(
      coordinate.y + box.height + offset > (viewBox.y + viewBox.height) ?
      coordinate.y - box.height - offset :
      coordinate.y + offset, viewBox.y);

    return (
      <Animate
        from={`translate(${translateX}px, ${translateY}px)`}
        to={`translate(${translateX}px, ${translateY}px)`}
        duration={animationDuration}
        isActive={isAnimationActive}
        easing={animationEasing}
        attributeName="transform"
      >
        <div
          className="recharts-tooltip-wrapper"
          style={outerStyle}
        >
          {contentItem}
        </div>
      </Animate>
    );
  }
}

export default Tooltip;
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import { Button } from 'react-bootstrap';
import { generateID } from '../utils/functions';
import Parameters from './Parameters';
import jsonString from 'json-string';

class Action extends Component{

  static propTypes = {
    action: PropTypes.object,
  };

  render(){
    const { action } = this.props;

    let bodyParams;
    let urlParams;
    let bodyParamsOutput;
    let urlParamsOutput;

    if(action.params){
      if(action.params.body) {
        bodyParams = action.params.body;
      }

      if(action.params.url) {
        urlParams = action.params.url;
      }
    }

    if(urlParams){
      urlParamsOutput = (

URL Parameters

          <Parameters parameters={urlParams} type={false} />

      );
    }

    if(bodyParams){
      bodyParamsOutput = (

Parameters

          <Parameters parameters={bodyParams} />

      );
    }

    // Need to generate the json response output from the json object here
    // so I can use it later.
    let responsesOutput = action.responses.map((response) => {
      return (

{response.name}

Status Code: {response.status}

Fields:

Example

            {`
              ${jsonString(response.body)}
            `}

      );
    });

    return (

        <Button bsStyle="success" className="pull-left">{action.method}</Button>
        <h3 id={`${generateID(action.name)}`}>
           {action.name}

        {urlParamsOutput}
        {bodyParamsOutput}

Responses

          {responsesOutput}

    );
  }
};
export default Action;
<commit_msg>Corrected glitch<commit_after>import React, {Component, PropTypes} from 'react';
import { Button } from 'react-bootstrap';
import { generateID } from '../utils/functions';
import Parameters from './Parameters';
import jsonString from 'json-string';

class Action extends Component{

  static propTypes = {
    action: PropTypes.object,
  };

  render(){
    const { action } = this.props;

    let bodyParams;
    let urlParams;
    let bodyParamsOutput;
    let urlParamsOutput;

    if(action.params){
      if(action.params.body) {
        bodyParams = action.params.body;
      }

      if(action.params.url) {
        urlParams = action.params.url;
      }
    }

    if(urlParams){
      urlParamsOutput = (

URL Parameters

          <Parameters parameters={urlParams} type={false} />

      );
    }

    if(bodyParams){
      bodyParamsOutput = (

Parameters

          <Parameters parameters={bodyParams} />

      );
    }

    // Need to generate the json response output from the json object here
    // so I can use it later.
    let responsesOutput = action.responses.map((response) => {
      return (

{response.name}

Status Code: {response.status}

Fields:

Example

            {`${jsonString(response.body)}`}

      );
    });

    return (

        <Button bsStyle="success" className="pull-left">{action.method}</Button>
        <h3 id={`${generateID(action.name)}`}>
           {action.name}

        {urlParamsOutput}
        {bodyParamsOutput}

Responses

          {responsesOutput}

    );
  }
};
export default Action;
<|endoftext|>


<commit_before>import React, { useState } from 'react';
import css from 'styled-jsx/css';
import Button from 'components/Button';
import { Mutation } from 'react-apollo';
import Me from 'lib/query/Me';
import { bp, color, fontSize } from 'lib/variables';
import AddSshKeyMutation from '../../lib/mutation/AddSshKey';

const AddSshKey = ({me: { id, email }}) => {

  const defaultValues = {sshKeyName: '', sshKey: '', sshKeyType: 'SSH_RSA'};
  const [values, setValues] = useState(defaultValues);

  const handleChange = e => {
    const {name, value} = e.target;
    setValues({...values, [name]: value});
  }

  const isFormValid = values.sshKeyName !== '' && values.sshKey !== '';

  return(

      <Mutation mutation={AddSshKeyMutation} refetchQueries={[{ query: Me }]}>
        {(addSshKey, { loading, called, error, data }) => {

          const addSshKeyHandler = () => {
            addSshKey({
              variables: {
                input: {
                  name: values.sshKeyName,
                  keyValue: values.sshKey.replace('ssh-rsa', '').replace('ssh-ed25519', '').trim(),
                  keyType: values.sshKeyType,
                  user: {
                    id,
                    email
                  }
                }
              }
            });
            setValues(defaultValues);
          };

          if (!error && called && loading) {
            return
Adding SSH Key...
;
          }

          return (

              { error ?
{error.message.replace('GraphQL error:', '').trim()}
 : "" }

                SSH Key Name
                <input
                  aria-labelledby="addSshKeyName"
                  id="sshKeyName"
                  name="sshKeyName"
                  label='SSH Key Name'
                  className="addSshKeyInput"
                  type="text"
                  value={values.sshKeyName}
                  onChange={handleChange}
                />

                SSH Key Type
                <select
                  id="sshKeyType"
                  name="sshKeyType"
                  onChange={handleChange}
                  aria-labelledby="addSshKeyType"
                  label='SSH Key Type'
                  className="addSshKeyInput"
                >
                  {['SSH_RSA', 'SSH_ED25519'].map(value => (
                    <option key={value} value={value}>
                      {value}
                    </option>
                  ))}
                </select>

                SSH Key
                <textarea
                  aria-labelledby="addSshKey"
                  id='sshKey'
                  name='sshKey'
                  label='SSH Key'
                  className="addSshKeyInput"
                  type="text"
                  onChange={handleChange}
                  value={values.sshKey}
                  placeholder="Begins with 'ssh-rsa', 'ssh-ed25519'"/>

              <Button disabled={!isFormValid} action={addSshKeyHandler}>Add</Button>

          );
        }}
      </Mutation>

  );
};

export default AddSshKey;
<commit_msg>Aria Label fixes<commit_after>import React, { useState } from 'react';
import css from 'styled-jsx/css';
import Button from 'components/Button';
import { Mutation } from 'react-apollo';
import Me from 'lib/query/Me';
import { bp, color, fontSize } from 'lib/variables';
import AddSshKeyMutation from '../../lib/mutation/AddSshKey';

const AddSshKey = ({me: { id, email }}) => {

  const defaultValues = {sshKeyName: '', sshKey: '', sshKeyType: 'SSH_RSA'};
  const [values, setValues] = useState(defaultValues);

  const handleChange = e => {
    const {name, value} = e.target;
    setValues({...values, [name]: value});
  }

  const isFormValid = values.sshKeyName !== '' && values.sshKey !== '';

  return(

      <Mutation mutation={AddSshKeyMutation} refetchQueries={[{ query: Me }]}>
        {(addSshKey, { loading, called, error, data }) => {

          const addSshKeyHandler = () => {
            addSshKey({
              variables: {
                input: {
                  name: values.sshKeyName,
                  keyValue: values.sshKey.replace('ssh-rsa', '').replace('ssh-ed25519', '').trim(),
                  keyType: values.sshKeyType,
                  user: {
                    id,
                    email
                  }
                }
              }
            });
            setValues(defaultValues);
          };

          if (!error && called && loading) {
            return
Adding SSH Key...
;
          }

          return (

              { error ?
{error.message.replace('GraphQL error:', '').trim()}
 : "" }

                SSH Key Name
                <input
                  id="sshKeyName"
                  name="sshKeyName"
                  className="addSshKeyInput"
                  type="text"
                  value={values.sshKeyName}
                  onChange={handleChange}
                />

                SSH Key Type
                <select
                  id="sshKeyType"
                  name="sshKeyType"
                  onChange={handleChange}
                  className="addSshKeyInput"
                >
                  {['SSH_RSA', 'SSH_ED25519'].map(value => (
                    <option key={value} value={value}>
                      {value}
                    </option>
                  ))}
                </select>

                SSH Key
                <textarea
                  id='sshKey'
                  name='sshKey'
                  className="addSshKeyInput"
                  type="text"
                  onChange={handleChange}
                  value={values.sshKey}
                  placeholder="Begins with 'ssh-rsa', 'ssh-ed25519'"/>

              <Button disabled={!isFormValid} action={addSshKeyHandler}>Add</Button>

          );
        }}
      </Mutation>

  );
};

export default AddSshKey;
<|endoftext|>