Socket
Socket
Sign inDemoInstall

schema-client

Package Overview
Dependencies
1
Maintainers
1
Versions
47
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 3.0.11 to 3.0.12

.prettierrc

27

lib/cache.js

@@ -32,3 +32,3 @@ var inherits = require('util').inherits;

writePerms: options.writePerms || DEFAULT_WRITE_PERMS,
indexLimit: options.indexLimit || DEFAULT_INDEX_LIMIT
indexLimit: options.indexLimit || DEFAULT_INDEX_LIMIT,
};

@@ -87,5 +87,10 @@

data = data || null;
var saneUrl = String(url).trim().replace(/^\/|\/$/g, '');
var keyData = JSON.stringify([ saneUrl, data ]);
return crypto.createHash('md5').update(keyData).digest('hex');
var saneUrl = String(url)
.trim()
.replace(/^\/|\/$/g, '');
var keyData = JSON.stringify([saneUrl, data]);
return crypto
.createHash('md5')
.update(keyData)
.digest('hex');
};

@@ -99,7 +104,9 @@

Cache.prototype.getPath = function(url, data) {
return this.params.path.replace(/\/$/, '') +
return (
this.params.path.replace(/\/$/, '') +
'/client.' +
this.params.clientId +
'.' +
Array.prototype.slice.call(arguments).join('.');
Array.prototype.slice.call(arguments).join('.')
);
};

@@ -314,3 +321,6 @@

}
} else if (invalid[collection] && this.indexes[collection][invalid[collection]] !== undefined) {
} else if (
invalid[collection] &&
this.indexes[collection][invalid[collection]] !== undefined
) {
// Clear a single index element by key

@@ -375,3 +385,3 @@ var key = invalid[collection];

Cache.prototype.resultCollections = function(result) {
var collections = result.$collection !== undefined ? [ result.$collection ] : [];
var collections = result.$collection !== undefined ? [result.$collection] : [];
// Combine $collection and $expanded headers

@@ -389,4 +399,3 @@ if (result.$expanded !== undefined) {

// Exports
exports.Cache = Cache;

@@ -14,3 +14,3 @@ var assert = require('chai').assert;

writePerms: '0644',
indexLimit: 1000
indexLimit: 1000,
});

@@ -24,3 +24,3 @@ });

writePerms: '1234',
indexLimit: 1
indexLimit: 1,
});

@@ -32,3 +32,3 @@ assert.deepEqual(cache.params, {

writePerms: '1234',
indexLimit: 1
indexLimit: 1,
});

@@ -40,3 +40,3 @@ });

var cache = new Cache('test', {
storage: 'fail'
storage: 'fail',
});

@@ -63,7 +63,11 @@ assert.fail('oops');

it('returns response object when cache index found', function() {
cache.put('/', {}, {
$data: 'foo',
$collection: 'bar',
$cached: { 'bar': 1 }
});
cache.put(
'/',
{},
{
$data: 'foo',
$collection: 'bar',
$cached: { bar: 1 },
},
);
var result = cache.get('/', {});

@@ -73,3 +77,3 @@ assert.deepEqual(result, {

$collection: 'bar',
$cached: true
$cached: true,
});

@@ -129,3 +133,3 @@ });

assert.deepEqual(versions, {
test: 1
test: 1,
});

@@ -149,3 +153,3 @@ });

assert.deepEqual(indexes, {
test: { '12345': 100 }
test: { '12345': 100 },
});

@@ -163,3 +167,3 @@ });

$collection: 'bar',
$cached: { 'bar': 1 }
$cached: { bar: 1 },
};

@@ -171,6 +175,6 @@ });

assert.deepEqual(cache.getIndex(), {
bar: { '58cd6550e4fe03ea78ee22cf52c759b7': 50 }
bar: { '58cd6550e4fe03ea78ee22cf52c759b7': 50 },
});
assert.deepEqual(cache.getVersions(), {
bar: 1
bar: 1,
});

@@ -180,3 +184,3 @@ assert.deepEqual(cache.get('/', {}), {

$collection: 'bar',
$cached: true
$cached: true,
});

@@ -192,3 +196,3 @@ });

assert.deepEqual(indexes, {
bar: { '12345': 100 }
bar: { '12345': 100 },
});

@@ -199,3 +203,3 @@ cache.putIndex('bar2', '123456', 1001);

bar: { '12345': 100 },
bar2: { '123456': 1001 }
bar2: { '123456': 1001 },
});

@@ -209,3 +213,3 @@ });

assert.deepEqual(indexes, {
bar: { '12345': 100 }
bar: { '12345': 100 },
});

@@ -223,11 +227,15 @@ cache.putIndex('bar', '12345', 1001);

var cache = new Cache('test');
cache.put('/', {}, {
$data: 'foo',
$collection: 'bar',
$cached: { 'bar': 1 }
});
cache.put(
'/',
{},
{
$data: 'foo',
$collection: 'bar',
$cached: { bar: 1 },
},
);
assert.deepEqual(cache.get('/', {}), {
$data: 'foo',
$collection: 'bar',
$cached: true
$cached: true,
});

@@ -234,0 +242,0 @@ cache.remove('/', {});

@@ -1,25 +0,16 @@

var events = require('events');
var crypto = require('crypto');
var inherits = require('util').inherits;
var Promise = require('bluebird').Promise;
const events = require('events');
const crypto = require('crypto');
const inherits = require('util').inherits;
const Promise = require('bluebird').Promise;
var Schema = require('./schema');
const Schema = require('./schema');
Schema.Connection = require('./connection').Connection;
Schema.Cache = require('./cache').Cache;
var DEFAULT_HOST = 'api.schema.io';
var DEFAULT_PORT = 8443;
var DEFAULT_VERIFY_CERT = true;
var DEFAULT_VERSION = 1;
const DEFAULT_HOST = 'api.schema.io';
const DEFAULT_PORT = 8443;
const DEFAULT_VERIFY_CERT = true;
const DEFAULT_VERSION = 1;
/**
* Client constructor
*
* @param string clientId
* @param string clientKey
* @param object options
* @param function callback
*/
var Client = function(clientId, clientKey, options, callback) {
const Client = function(clientId, clientKey, options, callback) {
events.EventEmitter.call(this);

@@ -40,9 +31,2 @@

/**
* Initialize client parameters
*
* @param string clientId
* @param string clientKey
* @param object options
*/
Client.prototype.init = function(clientId, clientKey, options) {

@@ -70,3 +54,3 @@ options = options || {};

routeClientId: options.route && options.route.client,
cache: typeof options.cache !== 'undefined' ? options.cache : true
cache: typeof options.cache !== 'undefined' ? options.cache : true,
};

@@ -82,7 +66,2 @@

/**
* Connect to server
*
* @param function callback
*/
Client.prototype.connect = function(callback) {

@@ -95,3 +74,3 @@ var self = this;

verifyCert: this.params.verifyCert,
timeout: self.params.timeout
timeout: self.params.timeout,
},

@@ -101,3 +80,3 @@ function() {

self.emit('connect', self);
}
},
);

@@ -109,3 +88,3 @@ this.server.on('close', function() {

if (events.EventEmitter.listenerCount(self, 'error')) {
self.emit('error', 'Error: '+err);
self.emit('error', 'Error: ' + err);
}

@@ -115,3 +94,3 @@ });

if (events.EventEmitter.listenerCount(self, 'error')) {
self.emit('error', 'Network Error: '+err, 'network');
self.emit('error', 'Network Error: ' + err, 'network');
}

@@ -121,3 +100,3 @@ });

if (events.EventEmitter.listenerCount(self, 'error')) {
self.emit('error', 'Protocol Error: '+err, 'protocol');
self.emit('error', 'Protocol Error: ' + err, 'protocol');
}

@@ -127,3 +106,3 @@ });

if (events.EventEmitter.listenerCount(self, 'error')) {
self.emit('error', 'Server Error: '+err, 'server');
self.emit('error', 'Server Error: ' + err, 'server');
}

@@ -133,10 +112,2 @@ });

/**
* Client request handler
*
* @param string method
* @param string url
* @param mixed data
* @param function callback
*/
Client.prototype.request = function(method, url, data, callback) {

@@ -160,5 +131,7 @@ if (typeof data === 'function') {

if (promises.length) {
return Promise.all(promises).bind(this).then(function() {
this.request(method, url, data, callback);
});
return Promise.all(promises)
.bind(this)
.then(function() {
this.request(method, url, data, callback);
});
}

@@ -169,3 +142,3 @@

data = {
$data: data !== undefined ? data : null
$data: data !== undefined ? data : null,
};

@@ -214,9 +187,2 @@

/**
* Resolve and return promises array from data
* Only resolve top level object keys
*
* @param object data
* @return array
*/
Client.prototype.promisifyData = function(data) {

@@ -255,11 +221,2 @@ if (!data) {

/**
* Client response handler
*
* @param string method
* @param string url
* @param mixed request
* @param mixed response
* @param function callback
*/
Client.prototype.respond = function(method, url, request, response, callback) {

@@ -279,3 +236,3 @@ var err = undefined;

}
if (response.$data && (typeof response.$data === 'object')) {
if (response.$data && typeof response.$data === 'object') {
responseData = Client.createResource(response.$url || url, response, this);

@@ -287,3 +244,3 @@ } else {

} else {
response = {$error: 'Empty response from server', $status: 500};
response = { $error: 'Empty response from server', $status: 500 };
err = response.$error;

@@ -294,10 +251,2 @@ }

/**
* Client GET request
*
* @param string url
* @param object data
* @param function callback
* @return mixed
*/
Client.prototype.get = function(url, data, callback) {

@@ -326,10 +275,2 @@ if (this.cache) {

/**
* Get result from cache if available
*
* @param string url
* @param object data
* @param function callback
* @return mixed
*/
Client.prototype.getCacheResult = function(url, data) {

@@ -365,7 +306,4 @@ var self = this;

});
}
};
/**
* Client PUT request
*/
Client.prototype.put = function(url, data, callback) {

@@ -375,5 +313,2 @@ return this.request('put', url, data, callback);

/**
* Client POST request
*/
Client.prototype.post = function(url, data, callback) {

@@ -383,5 +318,2 @@ return this.request('post', url, data, callback);

/**
* Client DELETE request
*/
Client.prototype.delete = function(url, data, callback) {

@@ -391,9 +323,2 @@ return this.request('delete', url, data, callback);

/**
* Client auth request
*
* @param object params
* @param function callback
* @return mixed;
*/
Client.prototype.auth = function(nonce, callback) {

@@ -421,8 +346,10 @@ var self = this;

// 2) Create key hash
var keyHash = crypto.createHash('md5')
.update(clientId + "::" + clientKey)
var keyHash = crypto
.createHash('md5')
.update(clientId + '::' + clientKey)
.digest('hex');
// 3) Create auth key
var authKey = crypto.createHash('md5')
var authKey = crypto
.createHash('md5')
.update(nonce + clientId + keyHash)

@@ -434,3 +361,3 @@ .digest('hex');

client: clientId,
key: authKey
key: authKey,
};

@@ -455,7 +382,2 @@ if (this.params.version) {

/**
* Close server connection
*
* @return void
*/
Client.prototype.close = function() {

@@ -467,11 +389,2 @@ if (this.server) {

/**
* Client create/init helper
*
* @param string clientId
* @param string clientKey
* @param object options
* @param function callback
* @return Client
*/
Client.create = function(clientId, clientKey, options, callback) {

@@ -481,10 +394,2 @@ return new Client(clientId, clientKey, options, callback);

/**
* Create a resource from response data
*
* @param string url
* @param mixed response
* @param Client client
* @return Resource
*/
Client.createResource = function(url, response, client) {

@@ -497,5 +402,4 @@ if (response && response.$data && 'count' in response.$data && response.$data.results) {

// Exports
module.exports = Schema;
module.exports.Client = Client;
module.exports.createClient = Client.create;

@@ -55,3 +55,3 @@ var assert = require('chai').assert;

it('init with options + callback', function() {
new Schema.Client('id', 'key', {}, function(){});
new Schema.Client('id', 'key', {}, function() {});

@@ -81,3 +81,3 @@ assert.strictEqual(initStub.calledOnce, true);

routeClientId: undefined,
cache: true
cache: true,
};

@@ -96,3 +96,3 @@ });

client = new Schema.Client('id', 'key', {
cache: false
cache: false,
});

@@ -106,3 +106,3 @@

testParams.clientKey = 'testKey';
client.init({id: 'testId', key: 'testKey'});
client.init({ id: 'testId', key: 'testKey' });

@@ -116,7 +116,3 @@ assert.deepEqual(client.params, testParams);

testParams.host = 'api2';
client.init(
testParams.clientId,
testParams.clientKey,
{host: testParams.host}
);
client.init(testParams.clientId, testParams.clientKey, { host: testParams.host });

@@ -132,6 +128,6 @@ assert.strictEqual(client.params.clientId, 'id2');

key: 'key',
route: {client: 'id2'}
route: { client: 'id2' },
});
assert.deepEqual(client.params.route, {client: 'id2'});
assert.deepEqual(client.params.route, { client: 'id2' });
assert.deepEqual(client.params.routeClientId, 'id2');

@@ -262,3 +258,3 @@ });

assert.deepEqual(serverRequestStub.args[0][2], {
$data: 'data'
$data: 'data',
});

@@ -269,3 +265,3 @@ });

client = new Schema.Client('id', 'key', {
route: {client: 'id2'}
route: { client: 'id2' },
});

@@ -282,5 +278,5 @@ client.authed = false;

$route: {
client: 'id2'
client: 'id2',
},
$cached: {}
$cached: {},
});

@@ -296,3 +292,3 @@ });

assert.deepEqual(serverRequestStub.args[0][2], {
$data: null
$data: null,
});

@@ -304,3 +300,3 @@ });

serverRequestStub.onCall(0).callsArgWith(3, {
$auth: true
$auth: true,
});

@@ -319,3 +315,3 @@ client.request('get', 'url', 'data');

$auth: true,
$end: true
$end: true,
});

@@ -334,3 +330,3 @@ client.request('get', 'url', 'data');

$status: 200,
$data: 'success'
$data: 'success',
});

@@ -342,3 +338,3 @@ client.request('get', 'url', 'data');

$status: 200,
$data: 'success'
$data: 'success',
});

@@ -349,3 +345,3 @@ });

serverRequestStub.onCall(0).callsArgWith(3, {
$data: 'success'
$data: 'success',
});

@@ -360,3 +356,3 @@

serverRequestStub.onCall(0).callsArgWith(3, {
$error: 'error'
$error: 'error',
});

@@ -373,7 +369,9 @@

var calledBack = false;
return client.request('get', 'url', 'data', function() {
calledBack = true;
}).then(function() {
assert.strictEqual(calledBack, true);
});
return client
.request('get', 'url', 'data', function() {
calledBack = true;
})
.then(function() {
assert.strictEqual(calledBack, true);
});
});

@@ -385,3 +383,3 @@

test2: Promise.resolve('world'),
test3: 'static'
test3: 'static',
};

@@ -393,3 +391,3 @@

test2: 'world',
test3: 'static'
test3: 'static',
});

@@ -400,12 +398,6 @@ });

it('resolves promised data (array)', function() {
var data = [
Promise.resolve('hello'),
Promise.resolve('world'),
'static'
];
var data = [Promise.resolve('hello'), Promise.resolve('world'), 'static'];
return client.request('get', 'url', data).then(function() {
assert.deepEqual(serverRequestStub.args[0][2].$data, [
'hello', 'world', 'static'
]);
assert.deepEqual(serverRequestStub.args[0][2].$data, ['hello', 'world', 'static']);
});

@@ -427,4 +419,4 @@ });

id: 1,
name: 'foo'
}
name: 'foo',
},
};

@@ -444,3 +436,3 @@

var response = {
$data: null
$data: null,
};

@@ -457,3 +449,3 @@

var response = {
$error: 'Internal Server Error'
$error: 'Internal Server Error',
};

@@ -510,3 +502,5 @@

var returnValue = 'response';
var getCacheResultStub = sinon.stub(Schema.Client.prototype, 'getCacheResult').returns(Promise.resolve(returnValue));
var getCacheResultStub = sinon
.stub(Schema.Client.prototype, 'getCacheResult')
.returns(Promise.resolve(returnValue));

@@ -518,3 +512,3 @@ var client = new Schema.Client();

getCacheResultStub.restore();
})
});

@@ -524,9 +518,11 @@ it('returns (error, response) when retrieving from cache', function() {

return client.get('url', 'data', function(error, response) {
assert.strictEqual(error, null);
assert.strictEqual(response, returnValue);
calledBack = true;
}).then(function() {
assert.strictEqual(calledBack, true);
});
return client
.get('url', 'data', function(error, response) {
assert.strictEqual(error, null);
assert.strictEqual(response, returnValue);
calledBack = true;
})
.then(function() {
assert.strictEqual(calledBack, true);
});
});

@@ -537,7 +533,9 @@

return client.get('url', function() {
calledBack = true;
}).then(function() {
assert.strictEqual(calledBack, true);
});
return client
.get('url', function() {
calledBack = true;
})
.then(function() {
assert.strictEqual(calledBack, true);
});
});

@@ -617,3 +615,3 @@ });

client: 'id',
key: 'db519c8947922ea94bdd541f8612f3fe'
key: 'db519c8947922ea94bdd541f8612f3fe',
});

@@ -657,4 +655,4 @@ });

count: 1,
results: [{}]
}
results: [{}],
},
};

@@ -668,3 +666,3 @@ var resource = Schema.Client.createResource('url', result, client);

var result = {
$data: {}
$data: {},
};

@@ -671,0 +669,0 @@ var resource = Schema.Client.createResource('url', result, client);

@@ -1,18 +0,11 @@

var inherits = require('util').inherits;
var events = require('events');
var tls = require('tls');
var net = require('net');
const inherits = require('util').inherits;
const events = require('events');
const tls = require('tls');
const net = require('net');
var DEFAULT_NETWORK_ERROR = 'Server unexpectedly closed network connection.';
var DEFAULT_TIMEOUT = 60000;
const DEFAULT_NETWORK_ERROR = 'Server unexpectedly closed network connection.';
const DEFAULT_TIMEOUT = 60000;
const RETRY_TIME = 3000;
/**
* Connection constructor
*
* @param string host
* @param int port
* @param object options
* @param function callback
*/
var Connection = function(host, port, options, callback) {
const Connection = function(host, port, options, callback) {
events.EventEmitter.call(this);

@@ -22,2 +15,4 @@

this.connected = false;
this.connectingTimeout = null;
this.connectingRetryTimeout = null;
this.buffer = [];

@@ -43,21 +38,29 @@ this.requestBuffer = [];

/**
* Initiate stream connection
*
* @param function callback
*/
Connection.prototype.connect = function(callback) {
var self = this;
var proto = this.options.clear ? net : tls;
var timeoutMs = this.options.timeout || DEFAULT_TIMEOUT;
this.stream = proto.connect({
host: this.host,
port: this.port,
rejectUnauthorized: this.options.verifyCert === false ? false : true
}, function() {
self.connected = true;
self.flushRequestBuffer();
callback && callback(self);
self.emit('connect');
});
if (!this.connectingTimeout) {
this.connectingTimeout = setTimeout(() => {
this.stream = null;
this.connectingTimeout = null;
this.flushRequestBufferWithError(`Connection timed out (${timeoutMs} ms)`);
}, timeoutMs);
}
this.stream = proto.connect(
{
host: this.host,
port: this.port,
rejectUnauthorized: this.options.verifyCert === false ? false : true,
},
() => {
this.connected = true;
clearTimeout(this.connectingTimeout);
this.connectingTimeout = null;
this.flushRequestBuffer();
callback && callback(this);
this.emit('connect');
},
);
this.stream.on('error', this.error.bind(this));

@@ -68,12 +71,5 @@ this.stream.on('data', this.receive.bind(this));

this.stream.setEncoding('utf8');
this.stream.setTimeout(this.options.timeout || DEFAULT_TIMEOUT);
this.stream.setTimeout(timeoutMs);
};
/**
* Call remote server method
*
* @param string method
* ...
* @param function response (last argument)
*/
Connection.prototype.request = function() {

@@ -96,10 +92,5 @@ // Copy args to avoid leaking

var request = JSON.stringify(args.slice(0, -1));
this.stream.write(request + "\n");
this.stream.write(request + '\n');
};
/**
* Receive data from the server
*
* @param object buffer
*/
Connection.prototype.receive = function(buffer) {

@@ -124,11 +115,6 @@ // Split buffer data on newline char

/**
* Handle server response data (JSON string)
*
* @param string data
*/
Connection.prototype.receiveResponse = function(data) {
var response;
var request = this.requestBuffer.shift();
var responder = request && request.pop();
let response;
const request = this.requestBuffer.shift();
const responder = request && request.pop();

@@ -142,7 +128,7 @@ if (responder === undefined) {

} catch (err) {
response = 'Unable to parse response from server ('+data+')';
response = 'Unable to parse response from server (' + data + ')';
this.emit('error.protocol', response);
return responder({
$status: 500,
$error: response
$error: response,
});

@@ -152,7 +138,7 @@ }

if (!response || typeof response !== 'object') {
response = 'Invalid response from server ('+data+')';
response = 'Invalid response from server (' + data + ')';
this.emit('error.protocol', response);
return responder({
$status: 500,
$error: response
$error: response,
});

@@ -174,16 +160,17 @@ }

/**
* Emit an error
*
* @param Error error
*/
Connection.prototype.error = function(error) {
const shouldReconnect =
!this.connected && this.stream && this.requestBuffer.length > 0 && !this.connectingRetryTimeout;
if (shouldReconnect) {
this.connectingRetryTimeout = setTimeout(() => {
this.connectingRetryTimeout = null;
this.connect();
}, RETRY_TIME);
}
this.emit('error', error);
};
/**
* Close this connection
*/
Connection.prototype.close = function() {
if (!this.connected) {
this.stream = null;
return;

@@ -205,5 +192,3 @@ }

/**
* Handle timeout by closing if no requests are pending
*/
// Handle timeout by closing if no requests are pending
Connection.prototype.timeout = function(error) {

@@ -216,7 +201,3 @@ if (this.requestBuffer.length) {

/**
* Flush local request buffer when connected
*
* @return void
*/
// FLush all requests when connected
Connection.prototype.flushRequestBuffer = function() {

@@ -226,4 +207,3 @@ if (!this.connected) {

}
var hasRequests = this.requestBuffer.length;
let hasRequests = this.requestBuffer.length;
while (--hasRequests >= 0) {

@@ -234,3 +214,17 @@ this.request.apply(this, this.requestBuffer.shift());

// Exports
// Flush all requests when a connection error occurs
Connection.prototype.flushRequestBufferWithError = function(error) {
let hasRequests = this.requestBuffer.length;
while (--hasRequests >= 0) {
const request = this.requestBuffer.shift();
const responder = request && request.pop();
if (typeof responder === 'function') {
responder({
$status: 500,
$error: error,
});
}
}
};
exports.Connection = Connection;
{
"name": "schema-client",
"version": "3.0.11",
"version": "3.0.12",
"description": "Schema API Client for NodeJS",

@@ -5,0 +5,0 @@ "keywords": [

SocketSocket SOC 2 Logo

Product

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc