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

jsonbeat

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jsonbeat - npm Package Compare versions

Comparing version 0.1.0 to 0.1.1

.npmignore

190

index.js

@@ -1,1 +0,189 @@

console.log('Comming soon');
'use strict';
var EventEmitter = require('events');
var util = require('util');
var JsonValidator = require('jsonvalidator');
var debug = require('debug')('jsonbeat');
var Jsonbeat = function(params) {
debug.enabled && debug(' + constructor begin ...');
EventEmitter.call(this);
params = params || {};
var context = {
validator: new JsonValidator()
}
var validobj = validateConstructor.call(context, params, Jsonbeat.constructorSchema);
if (validobj && validobj.failed === true) {
throw new Error('Jsonbeat constructor arguments are invalid');
}
params.eventName = params.eventName || params.name || 'transformed';
params.transform = params.transform || function(obj) { return obj };
if (typeof(params.transform) !== 'function') {
throw new Error('constructor "transform" field must be a node-callback function');
}
var self = this;
self.push = function(data, opts, callback) {
opts = opts || {};
var inputValidation = null;
if (params.inputSchema && params.skipInputValidation !== true) {
inputValidation = validateData.call(context, data, params.inputSchema);
}
var ret = null;
if (inputValidation && inputValidation.failed !== false) {
var transformed = { name: target.name, status: Jsonbeat.STATUS.INVALID_INPUTDATA }
self.emit(params.eventName, transformed);
ret = Promise.resolve(transformed);
} else {
ret = invokeAsyncFunction(data, params.transform).then(function(result) {
var transformed = {
name: params.name,
status: Jsonbeat.STATUS.OK,
result: result
};
var outputValidation = null;
if (params.outputSchema
&& params.skipOutputValidation !== true
&& !opts.skipOutputValidation) {
outputValidation = validateData.call(context, result, params.outputSchema);
}
if (outputValidation && outputValidation.failed !== false) {
transformed.status = Jsonbeat.STATUS.INVALID_OUTPUTDATA;
}
self.emit(params.eventName, transformed);
return transformed;
});
}
return applyCallback(ret, callback);
};
self.pushSync = function(data, opts) {
opts = opts || {};
var inputValidation = null;
if (params.inputSchema && params.skipInputValidation !== true) {
inputValidation = validateData.call(context, data, params.inputSchema);
}
var transformed = null;
if (inputValidation && inputValidation.failed !== false) {
transformed = { name: target.name, status: Jsonbeat.STATUS.INVALID_INPUTDATA }
} else {
var result = params.transform(data);
transformed = {
name: params.name,
status: Jsonbeat.STATUS.OK,
result: result
}
var outputValidation = null;
if (params.outputSchema
&& params.skipOutputValidation !== true
&& !opts.skipOutputValidation) {
outputValidation = validateData.call(context, result, params.outputSchema);
}
if (outputValidation && outputValidation.failed !== false) {
transformed.status = Jsonbeat.STATUS.INVALID_OUTPUTDATA;
}
}
self.emit(params.eventName, transformed);
return transformed;
}
debug.enabled && debug(' - constructor end!');
};
util.inherits(Jsonbeat, EventEmitter);
Jsonbeat.constructorSchema = {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"eventName": {
"type": "string"
},
"inputSchema": {
"type": "object",
"oneOf": [{
"$ref": "http://json-schema.org/draft-04/schema#"
}]
},
"skipInputValidation": {
"type": "boolean"
},
"transform": {},
"outputSchema": {
"type": "object",
"oneOf": [{
"$ref": "http://json-schema.org/draft-04/schema#"
}]
},
"skipOutputValidation": {
"type": "boolean"
}
},
"required": [ "transform" ]
};
Jsonbeat.STATUS = {
OK: 'OK',
INVALID_INPUTDATA: 'INVALID_INPUTDATA',
INVALID_OUTPUTDATA: 'INVALID_OUTPUTDATA',
ERROR: 'ERROR'
};
var validateConstructor = function(data, schema) {
return this.validator.validate(data, schema);
}
var validateData = function(data, schema) {
return this.validator.validate(data, schema);
}
var invokeAsyncFunction = function(x, f) {
var fPromise = new Promise(function(resolve, reject) {
var fcall = f(x, function(error, value) {
if (error) reject(error);
resolve(value);
});
if (fcall) {
if (typeof(fcall.then) === 'function') {
debug.enabled && debug('invokeAsyncFunction() - return a Promise');
} else {
debug.enabled && debug('invokeAsyncFunction() - return a value');
}
resolve(fcall);
} else {
debug.enabled && debug('invokeAsyncFunction() - invalid async function');
reject(new Error('transform() must have callback or return a value/promise'));
}
});
return fPromise;
}
var applyCallback = function(reqPromise, callback) {
if (callback && typeof(callback) === 'function') {
reqPromise.then(function(data) {
callback(null, data);
debug.enabled && debug("Execution has completed successfully");
}).catch(function (error) {
callback({ error: error, message: 'transform() occurred an error' });
debug.enabled && debug("Execution failed: " + JSON.stringify(error));
});
} else {
return reqPromise;
}
}
module.exports = Jsonbeat;
{
"name": "jsonbeat",
"version": "0.1.0",
"version": "0.1.1",
"description": "A step of JSON transforming flow",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "node_modules/.bin/mocha test/tdd/*-test.js"
},
"author": "devebot",
"license": "MIT"
"license": "MIT",
"dependencies": {
"bluebird": "^3.4.7",
"debug": "^2.6.1",
"jsonvalidator": "^0.1.1",
"loadsync": "^0.1.4"
},
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^3.2.0"
}
}
# jsonbeat
> A step of JSON transforming flow
## Install
```shell
npm install --save jsonbeat
```
## Example
Define the `transformer`:
```javascript
var jsonbeat = require('jsonbeat');
var billSchema = {
name: 'Summary',
inputSchema: {
"type": "object",
"properties": {
"title": { "type": "string" },
"fromTime": { "type": "string" },
"toTime": { "type": "string" },
"customerId": { "type": "string" },
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"label": { "type": "string" },
"price": { "type": "number" },
"amount": { "type": "number" }
},
"required": ["label", "price", "amount"]
}
}
}
},
transform: function(data) {
var summary = data.items.reduce(function(sum, item) {
sum.count += item.amount;
sum.total += item.amount * item.price;
return sum;
}, { count: 0, total: 0 });
return {
title: data.title + ' [' + data.customerId + ']',
customerId: data.customerId,
count: summary.count,
total: summary.total
}
}
};
var billSchemaCallback = Object.assign({}, billSchema, {
transform: function(data, callback) {
var summary = data.items.reduce(function(sum, item) {
sum.count += item.amount;
sum.total += item.amount * item.price;
return sum;
}, { count: 0, total: 0 });
var ret = {
title: data.title + ' [' + data.customerId + ']',
customerId: data.customerId,
count: summary.count,
total: summary.total
}
callback && callback(null, ret);
return ret;
}
});
var transformer1 = new jsonbeat(billSchema);
transformer1.on('Summary', function(result) {
console.log('Summary (transformer1): %s', JSON.stringify(result));
});
var transformer2 = new jsonbeat(billSchemaCallback);
transformer2.on('Summary', function(result) {
console.log('Summary (transformer2): %s', JSON.stringify(result));
});
```
Use the `transformer`:
```javascript
// use pushSync if transform function is synchronous
var result = transformer1.pushSync({
title: 'JsonFork Billing',
customerId: 'hello.com',
items: [
{ label: 'Item#1', price: 15, amount: 2 },
{ label: 'Item#2', price: 17, amount: 3 }
]
});
console.log('pushSync() output: %s', JSON.stringify(result, null, 2));
// use push() + promise if transform function is asynchronous
transformer2.push({
title: 'JsonFork Billing',
customerId: 'hello.com',
items: [
{ label: 'Item#1', price: 15, amount: 2 },
{ label: 'Item#2', price: 17, amount: 3 }
]
}).then(function(summary) {
console.log('push() output: %s', JSON.stringify(summary, null, 2));
});
```
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