Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

chaosrouter

Package Overview
Dependencies
Maintainers
1
Versions
47
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

chaosrouter - npm Package Compare versions

Comparing version 0.1.6 to 0.1.7

279

chaosrouter.js

@@ -5,12 +5,21 @@

var fs = require('fs');
var util = require('util');
var validationlib = {
"is_digit": function(value, kwargs) {
return value.isdigit();
"is_digit": function(values, kwargs, db, callback) {
for(var i=0; i<values.length; i++) {
if( isNaN(values[i]) ) {
return callback(false);
}
}
return callback(true);
},
"is_number": function(value, kwargs) {
return value.is_number();
},
"not_empty": function(value, kwargs) {
return value.strip() !== "";
"not_empty": function(values, kwargs, db, callback) {
var ch = true
for(var i=0; i<values.length; i++) {
if( values[i].trim() === "" ) {
return callback(false);
}
}
return callback(true);
}

@@ -25,2 +34,55 @@ }

}
function is_dict(d) {
return d.constructor.name == 'Object';
}
function is_iterable(d) {
try {
for( var i in d ) continue;
} catch(err) {
return false;
}
return true;
}
function is_string(d) {
return typeof d == 'string';
}
function dictcopy(dict) {
var copy = {}
for( var i in dict ) {
copy[i] = dict[i]
}
return copy
}
function format(str) {
for( var i=1; i < arguments.length; i++ ) {
var arg = arguments[i];
if( is_dict(arg) ) {
for( var k in arg ) {
var re = new RegExp( RegExp.escape("{"+k+"}"), 'g' );
str = str.replace(re, arg[k]);
}
}
else {
var re = new RegExp( RegExp.escape("{"+(i-1)+"}"), 'g' );
str = str.replace(re, arg);
}
}
return str;
}
function fill(s, data) {
if (s.indexOf(':<') === 0)
return data[s.slice(2).trim() ]
var v = format(s, data)
if (s.indexOf(':') === 0) {
try {
v = eval(v.slice(1));
} catch (err) {
v = null;
}
}
return v;
}
function ChaosRouter(data, db, basepath) {

@@ -34,2 +96,3 @@ if (! (this instanceof ChaosRouter))

if (is_dict(data))

@@ -40,3 +103,3 @@ this.config = data;

else
throw new Error("Unrecognized data type: {0}".format(type(data)))
throw new Error(format("Unrecognized data type: {0}", typeof data))
}

@@ -47,10 +110,12 @@ ChaosRouter.prototype.set_db = function(db) {

ChaosRouter.prototype.extend_methods = function(dict) {
dict.iteritems(function(k,v) {
methodlib[k] = v;
});
for( var k in dict) {
var v = dict[k];
methodlib[k] = v;
}
}
ChaosRouter.prototype.extend_validation = function(dict) {
dict.iteritems(function(k,v) {
validationlib[k] = v;
});
for( var k in dict) {
var v = dict[k];
validationlib[k]= v;
}
}

@@ -66,10 +131,13 @@ ChaosRouter.prototype.route = function(path, data, parents) {

if (data === null || path.startswith('/')) {
if (data === null || path.indexOf('/') === 0) {
data = this.config;
parents = [['', data]];
if (path.startswith(this.basepath))
path = path.slice(len(this.basepath));
if (path.indexOf(this.basepath) === 0)
path = path.slice(this.basepath.length);
}
var segs = path.strip('/').split('/');
// Remove leading and trailing slashes.
var _p = path.replace(/^\//, "").replace(/\/*$/, "")
var segs = _p.split('/');
if (!path)

@@ -82,13 +150,15 @@ return Endpoint(this.config, variables, parents, this.db);

data = parents.pop()[1];
return;
continue;
}
if (data.Get(seg) === null) {
if (data[seg] === undefined) {
var vkeys = [];
data.keys().iterate(function(v) {
if (v.strip().startswith(':'))
vkeys.append(v.strip());
});
var vkey = len(vkeys) > 0 ? vkeys.pop() : null;
data = vkey === null ? null : data.Get(vkey);
var _keys = Object.keys(data);
for( var k in _keys ){
var v = _keys[k];
if (v.trim().indexOf(':') === 0)
vkeys.push(v.trim());
}
var vkey = vkeys.length > 0 ? vkeys.pop() : null;
data = vkey === null ? null : data[vkey];

@@ -101,13 +171,13 @@ if (data === null)

else
data = data.Get(seg);
parents.append([seg,data]);
data = data[seg];
parents.push([seg,data]);
}
parents.pop();
if (data.Get('.base') === null)
var config = data.copy();
if (data['.base'] === undefined)
var config = dictcopy(data);
else {
var base = this.route( data.Get('.base'), data, parents );
var config = base.config.copy();
config.update(data);
var base = this.route( data['.base'], data, parents );
var config = dictcopy(base.config);
util._extend(config, data);
}

@@ -119,4 +189,4 @@

function fill(s, data) {
var v = s.format(data)
if (s.startswith(':')) {
var v = format(s, data)
if (s.indexOf(':') === 0) {
try {

@@ -143,9 +213,13 @@ v = eval(v.slice(1));

Endpoint.prototype.set_arguments = function(args) {
if (!is_iterable(args))
if (!is_iterable(args)) {
return false;
['db', 'value', 'path'].iterate(function(reserved) {
if (reserved.in(args))
}
var reserved_keys = ['db', 'value', 'path'];
for(var i=0; i<reserved_keys.length; i++) {
var reserved = reserved_keys[i];
if (args[reserved])
delete args[reserved];
});
this.args.update(args);
}
for ( var name in args )
this.args[name] = args[name];
}

@@ -158,8 +232,11 @@ Endpoint.prototype.validate = function(validations) {

var promises = [];
validations.iterate(function(rule) {
if (! is_list(rule) || len(rule) === 0)
throw new Error("Failed to process rule: {0}".format(rule));
for (var k in validations) {
var rule = validations[k];
if (! util.isArray(rule) || rule.length === 0)
throw new Error(format("Failed to process rule: {0}", rule));
var command = rule[0];
var params = [];
rule.slice(1).iterate(function(param) {
var _p = rule.slice(1);
for( var i=0; i<_p.length; i++) {
var param = _p[i];
try {

@@ -171,13 +248,13 @@ var value = fill(param, self.args);

}
params.append(value);
});
var cmd = validationlib.Get(command);
params.push(value);
}
var cmd = validationlib[command];
if (cmd === null)
throw new Error("No validation method for rule {0}".format(rule));
promises.append(new Promise(function(f,r){
cmd.call(validationlib, function(check) {
throw new Error(format("No validation method for rule {0}", rule));
promises.push(new Promise(function(f,r){
cmd.call(validationlib, params, self.args, self.db, function(check) {
if (is_dict(check))
r(check);
if (check !== true) {
var message = "Failed at rule {0} with values {1}".format(rule, params);
else if (check !== true) {
var message = format("Failed at rule {0} with values {1}", rule, params);
r({

@@ -188,32 +265,39 @@ "error": "Failed Validation",

}
f();
}, params, self.args, self.db);
else
f();
});
}));
});
}
return Promise.all(promises);
}
Endpoint.prototype.query = function() {
this.table = this.config.Get('.table');
this.where = this.config.Get('.where');
this.joins = this.config.Get('.join');
this.table = this.config['.table'];
this.where = this.config['.where'];
this.joins = this.config['.join'];
if (this.joins === null)
if (this.joins === undefined) {
var joins = '';
}
else {
var joins = [];
this.joins.iterate(function(join) {
for(var i=0; i<this.joins.length; i++) {
var join = this.joins[i];
var t = join[0];
var s = "`{0}`.`{1}`";
var c1 = s.format.apply(s, join[1] )
var c2 = s.format.apply(s, join[2] )
joins.append("{0} ON {1} = {2}".format(t,c1,c2))
});
joins = " LEFT JOIN " + " LEFT JOIN ".join(joins);
join[1].unshift(s);
join[2].unshift(s);
var c1 = format.apply( this, join[1] )
var c2 = format.apply( this, join[2] )
joins.push(format("{0} ON {1} = {2}", t,c1,c2))
}
joins = " LEFT JOIN " + joins.join(" LEFT JOIN ");
}
if (this.where === null)
if (this.where === undefined) {
var where = '';
else
var where = " WHERE {0} ".format(fill(this.where, this.args));
var query = " SELECT * FROM {table}{join}{where} ".format({
}
else {
var where = format(" WHERE {0} ", fill(this.where, this.args));
}
var query = format(" SELECT * FROM {table}{join}{where} ", {
'table': this.table,

@@ -224,18 +308,19 @@ 'join': joins,

query = query.format(this.args);
query = format(query, this.args);
return query;
}
Endpoint.prototype.get_structure = function() {
var structure = this.config.Get('.structure');
if (structure === null)
var structure = this.config['.structure'];
if (structure === undefined)
return false;
structure = structure.copy();
var update = this.config.Get('.structure_update');
if (update !== null) {
structure.update( update );
structure.iteritems(function(k,v) {
structure = dictcopy(structure);
var update = this.config['.structure_update'];
if (update !== undefined) {
util._extend( structure, update );
for( var k in structure) {
var v = structure[k];
if (v === false)
delete structure[k];
});
}
}

@@ -248,10 +333,10 @@

return new Promise(function(f,r) {
self.validate(self.config.Get('.validate'))
self.validate(self.config['.validate'])
.then(function() {
try {
var method = self.config.Get('.method');
if (method !== null) {
var cmd = methodlib.Get(method);
if (cmd === null)
throw new Error("No method named {0}".format(method));
var method = self.config['.method'];
if (method !== undefined) {
var cmd = methodlib[method];
if (cmd === undefined)
throw new Error(format("No method named {0}", method));
else

@@ -271,3 +356,6 @@ return cmd.call(methodlib, function(result) {

var query = self.query();
self.db.all(query, function(err, all) {
var q_callback = function(err, all) {
if(err !== undefined && err !== null)
return f(err);
var result = structure === null

@@ -277,10 +365,25 @@ ? all

return f(result);
});
}
// Check if using MySQL DB
if( self.db.query !== undefined ) {
self.db.query( query, q_callback );
}
// Check if using SQLite DB
else if( self.db.all !== undefined ) {
self.db.all( query, q_callback );
}
else {
return f({
"error": "Unsupported DB",
"message": "The database provided is not supported."
});
}
}
} catch (err) {
console.log(err)
r(err);
}
}, function(error) {
if (isinstance(error, Error)) {
if ( error instanceof Error ) {
r(error);

@@ -287,0 +390,0 @@ }

{
"name": "chaosrouter",
"version": "0.1.6",
"version": "0.1.7",
"description": "ERROR: No README data found!",

@@ -9,3 +9,5 @@ "main": "chaosrouter.js",

},
"author": "Matthew Brisebois",
"author": {
"name": "Matthew Brisebois"
},
"license": "GPLv3",

@@ -20,5 +22,9 @@ "repository": {

"dependencies": {
"restruct-data": "^0.1.3"
"restruct-data": "^0.1.7"
},
"devDependencies": {}
"devDependencies": {},
"readme": "ERROR: No README data found!",
"_id": "chaosrouter@0.1.4",
"_shasum": "effc9dfb74755ab377e7c8774c4d43dbc4e06eba",
"_from": "chaosrouter@^0.1.3"
}

@@ -13,5 +13,5 @@

endpoint = router.route('/get/people');
endpoint.execute(function (result) {
endpoint.execute().then( function (result) {
console.log( JSON.stringify(result, null, 4) );
});
console.log("Tests ran.")
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc