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

node-webhooks

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

node-webhooks - npm Package Compare versions

Comparing version 1.1.3 to 1.1.4

31

example.js
// Initialize WebHooks module.
var WebHooks = require('./index');
var WebHooks = require('./index')
var webHooks = new WebHooks({
db: './webHooksDB.json' // json file that store webhook URLs
});
db: './webHooksDB.json' // json file that store webhook URLs
})
// sync instantation - add a new webhook called 'shortname1'
webHooks.add('shortname1', 'http://127.0.0.1:9000/prova/other_url').then(function(){
// done
}).catch(function(err){
console.log(err);
});
webHooks.add('shortname1', 'http://127.0.0.1:9000/prova/other_url').then(function () {
// done
}).catch(function (err) {
console.log(err)
})
// add another webHook
webHooks.add('shortname2', 'http://127.0.0.1:9000/prova2/').then(function(){
// done
}).catch(function(err){
console.log(err);
});
webHooks.add('shortname2', 'http://127.0.0.1:9000/prova2/').then(function () {
// done
}).catch(function (err) {
console.log(err)
})

@@ -30,3 +29,3 @@ // remove a single url attached to the given shortname

// trigger a specific webHook
webHooks.trigger('shortname1', {data: 123});
webHooks.trigger('shortname2', {data: 123456}, {header: 'header'}); // payload will be sent as POST request with JSON body (Content-Type: application/json) and custom header
webHooks.trigger('shortname1', {data: 123})
webHooks.trigger('shortname2', {data: 123456}, {header: 'header'}) // payload will be sent as POST request with JSON body (Content-Type: application/json) and custom header

@@ -7,7 +7,7 @@ /*

{
"shortname1": [url1, url2, ...],
"shortname2": [url3, url4, ...],
...
...
"shortnameX": [urlZ, ...]
"shortname1": [url1, url2, ...],
"shortname2": [url3, url4, ...],
...
...
"shortnameX": [urlZ, ...]
}

@@ -17,107 +17,106 @@

var debug = require('debug')('node-webhooks');
var Promise = require('bluebird'); // for backward compatibility
var _ = require('lodash');
var jsonfile = require('jsonfile');
var fs = require('fs');
var crypto = require('crypto');
var request = require('request');
var events = require('eventemitter2');
var debug = require('debug')('node-webhooks')
var Promise = require('bluebird') // for backward compatibility
var _ = require('lodash')
var jsonfile = require('jsonfile')
var fs = require('fs')
var crypto = require('crypto')
var request = require('request')
var events = require('eventemitter2')
// will contain all the functions. We need to store them to be able to remove the listener callbacks
var _functions = {};
var _functions = {}
// WebHooks Class
function WebHooks(options){
if (typeof options !== 'object') throw new TypeError('Expected an Object');
if (typeof options.db !== 'string') throw new TypeError('db Must be a String path');
function WebHooks (options) {
if (typeof options !== 'object') throw new TypeError('Expected an Object')
if (typeof options.db !== 'string') throw new TypeError('db Must be a String path')
this.db = options.db;
this.db = options.db
this.emitter = new events.EventEmitter2({ wildcard: true });
this.emitter = new events.EventEmitter2({ wildcard: true })
var self = this;
// sync loading:
try{
fs.accessSync(this.db, fs.R_OK | fs.W_OK);
//DB already exists, set listeners for every URL.
debug('webHook DB loaded, setting listeners...');
_setListeners(self);
} catch(e){ // DB file not found, initialize it
if (e.hasOwnProperty('code')){
if (e.code === 'ENOENT'){ // file not found, init DB:
debug('webHook DB init');
_initDB(self.db);
} else console.error(e);
} else console.error(e);
}
var self = this
// sync loading:
try {
fs.accessSync(this.db, fs.R_OK | fs.W_OK)
// DB already exists, set listeners for every URL.
debug('webHook DB loaded, setting listeners...')
_setListeners(self)
} catch (e) {
// DB file not found, initialize it
if (e.hasOwnProperty('code')) {
if (e.code === 'ENOENT') {
// file not found, init DB:
debug('webHook DB init')
_initDB(self.db)
} else console.error(e)
} else console.error(e)
}
}
function _initDB(file){
// init DB.
var db = {}; // init empty db
jsonfile.writeFileSync(file, db, {spaces: 2});
function _initDB (file) {
// init DB.
var db = {} // init empty db
jsonfile.writeFileSync(file, db, {spaces: 2})
}
function _setListeners(self){
// set Listeners - sync method
function _setListeners (self) {
// set Listeners - sync method
try{
var obj = jsonfile.readFileSync(self.db);
if (!obj) throw Error('can\'t read webHook DB content');
try {
var obj = jsonfile.readFileSync(self.db)
if (!obj) throw Error('can\'t read webHook DB content')
for (var key in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue;
for (var key in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue
var urls = obj[key];
urls.forEach(function(url){
var enc_url = crypto.createHash('md5').update(url).digest('hex');
_functions[enc_url] = _getRequestFunction(self, url);
self.emitter.on(key, _functions[enc_url]);
});
}
}catch(e){
throw Error(e);
}
var urls = obj[key]
urls.forEach(function (url) {
var encUrl = crypto.createHash('md5').update(url).digest('hex')
_functions[encUrl] = _getRequestFunction(self, url)
self.emitter.on(key, _functions[encUrl])
})
}
} catch (e) {
throw Error(e)
}
// console.log(_functions[0] == _functions[1]);
// console.log(_functions[1] == _functions[2]);
// console.log(_functions[0] == _functions[2]);
// console.log(_functions[0] == _functions[1]);
// console.log(_functions[1] == _functions[2]);
// console.log(_functions[0] == _functions[2]);
}
function _getRequestFunction(self, url){
// return the function then called by the event listener.
var func = function(shortname, json_data, headers_data){ // argument required when eventEmitter.emit()
var obj = {'Content-Type': 'application/json'};
var headers = headers_data ? _.merge(obj, headers_data) : obj;
function _getRequestFunction (self, url) {
// return the function then called by the event listener.
var func = function (shortname, jsonData, headersData) { // argument required when eventEmitter.emit()
var obj = {'Content-Type': 'application/json'}
var headers = headersData ? _.merge(obj, headersData) : obj
debug('POST request to:', url);
// POST request to the instantiated URL with custom headers if provided
request({
method: 'POST',
uri: url,
strictSSL: false,
headers: headers,
body: JSON.stringify(json_data)
},
function (error, response, body) {
var statusCode = response ? response.statusCode : null;
body = body ? body : null;
debug('Request sent - Server responded with:', statusCode, body);
debug('POST request to:', url)
// POST request to the instantiated URL with custom headers if provided
request({
method: 'POST',
uri: url,
strictSSL: false,
headers: headers,
body: JSON.stringify(jsonData)
},
function (error, response, body) {
var statusCode = response ? response.statusCode : null
body = body || null
debug('Request sent - Server responded with:', statusCode, body)
if ((error || statusCode !== 200 )) {
self.emitter.emit(shortname + '.failure', shortname, statusCode, body);
return debug('HTTP failed: '+ error);
}
if ((error || statusCode !== 200)) {
self.emitter.emit(shortname + '.failure', shortname, statusCode, body)
return debug('HTTP failed: ' + error)
}
self.emitter.emit(shortname + '.success', shortname, statusCode, body);
}
);
self.emitter.emit(shortname + '.success', shortname, statusCode, body)
}
)
}
};
return func;
return func
}

@@ -127,203 +126,181 @@

WebHooks.prototype.trigger = function(shortname, json_data, headers_data) {
// trigger a webHook
this.emitter.emit(shortname, shortname, json_data, headers_data);
};
WebHooks.prototype.trigger = function (shortname, jsonData, headersData) {
// trigger a webHook
this.emitter.emit(shortname, shortname, jsonData, headersData)
}
WebHooks.prototype.add = function(shortname, url) { // url is required
// add a new webHook.
if (typeof shortname !== 'string') throw new TypeError('shortname required!');
if (typeof url !== 'string') throw new TypeError('Url must be a string');
WebHooks.prototype.add = function (shortname, url) { // url is required
// add a new webHook.
if (typeof shortname !== 'string') throw new TypeError('shortname required!')
if (typeof url !== 'string') throw new TypeError('Url must be a string')
var self = this;
return new Promise(function(resolve, reject){
var self = this
return new Promise(function (resolve, reject) {
try {
var obj = jsonfile.readFileSync(self.db)
if (!obj) throw Error('can\'t read webHook DB content')
try{
var modified = false
var encUrl
if (obj[shortname]) {
// shortname already exists
if (obj[shortname].indexOf(url) === -1) {
// url doesn't exists for given shortname
debug('url added to an existing shortname!')
obj[shortname].push(url)
encUrl = crypto.createHash('md5').update(url).digest('hex')
_functions[encUrl] = _getRequestFunction(self, url)
self.emitter.on(shortname, _functions[encUrl])
modified = true
}
} else {
// new shortname
debug('new shortname!')
obj[shortname] = [url]
encUrl = crypto.createHash('md5').update(url).digest('hex')
_functions[encUrl] = _getRequestFunction(self, url)
self.emitter.on(shortname, _functions[encUrl])
modified = true
}
var obj = jsonfile.readFileSync(self.db);
if (!obj) throw Error('can\'t read webHook DB content');
// actualize DB
if (modified) {
jsonfile.writeFileSync(self.db, obj)
resolve(true)
} else resolve(false)
} catch (e) {
reject(e)
}
})
}
var modified = false;
if (obj[shortname]){
// shortname already exists
if (obj[shortname].indexOf(url) === -1){
// url doesn't exists for given shortname
debug('url added to an existing shortname!');
obj[shortname].push(url);
var enc_url = crypto.createHash('md5').update(url).digest('hex');
_functions[enc_url] = _getRequestFunction(self, url);
self.emitter.on(shortname, _functions[enc_url]);
modified = true;
}
}else{
// new shortname
debug('new shortname!');
obj[shortname] = [url];
var enc_url = crypto.createHash('md5').update(url).digest('hex');
_functions[enc_url] = _getRequestFunction(self, url);
self.emitter.on(shortname, _functions[enc_url]);
modified = true;
}
WebHooks.prototype.remove = function (shortname, url) { // url is optional
// if url exists remove only the url attached to the selected webHook.
// else remove the webHook and all the attached URLs.
if (typeof shortname !== 'string') {
throw new TypeError('shortname required!')
}
var self = this
return new Promise(function (resolve, reject) {
// Basically removeListener will look up the given function by reference, if it found that function it will remove it from the event hander.
try {
if (typeof url !== 'undefined') {
// save in db
_removeUrlFromShortname(self, shortname, url, function (err, done) {
if (err) return reject(err)
if (done) {
// remove only the specified url
var urlKey = crypto.createHash('md5').update(url).digest('hex')
self.emitter.removeListener(shortname, _functions[urlKey])
delete _functions[urlKey]
resolve(true)
} else resolve(false)
})
} else {
// remove every event listener attached to the webHook shortname.
self.emitter.removeAllListeners(shortname)
// actualize DB
if (modified){
jsonfile.writeFileSync(self.db, obj);
resolve(true);
} else resolve(false);
// delete all the callbacks in _functions for the specified shortname. Let's loop over the url taken from the DB.
var obj = jsonfile.readFileSync(self.db)
if (obj.hasOwnProperty(shortname)) {
var urls = obj[shortname]
urls.forEach(function (url) {
var urlKey = crypto.createHash('md5').update(url).digest('hex')
delete _functions[urlKey]
})
// save it back to the DB
_removeShortname(self, shortname, function (err) {
if (err) return reject(err)
resolve(true)
})
} else {
debug('webHook doesn\'t exists')
resolve(false)
}
}
} catch (e) {
reject(e)
}
})
}
}catch(e){
reject(e);
}
function _removeUrlFromShortname (self, shortname, url, callback) {
try {
var obj = jsonfile.readFileSync(self.db)
});
};
WebHooks.prototype.remove = function(shortname, url) { // url is optional
// if url exists remove only the url attached to the selected webHook.
// else remove the webHook and all the attached URLs.
if (typeof shortname === 'undefined') throw new TypeError('shortname required!');
var self = this;
return new Promise(function(resolve, reject){
// Basically removeListener will look up the given function by reference, if it found that function it will remove it from the event hander.
try{
if (typeof url !== 'undefined'){
// save in db
_removeUrlFromShortname(self, shortname, url, function(err, done){
if (err) return reject(err);
if (done){
// remove only the specified url
var url_key = crypto.createHash('md5').update(url).digest('hex');
self.emitter.removeListener(shortname, _functions[url_key]);
delete _functions[url_key];
resolve(true);
}
else resolve(false);
});
}else{
// remove every event listener attached to the webHook shortname.
self.emitter.removeAllListeners(shortname);
// delete all the callbacks in _functions for the specified shortname. Let's loop over the url taken from the DB.
var obj = jsonfile.readFileSync(self.db);
if (obj.hasOwnProperty(shortname)){
var urls = obj[shortname];
urls.forEach(function(url){
var url_key = crypto.createHash('md5').update(url).digest('hex');
delete _functions[url_key];
});
// save it back to the DB
_removeShortname(self, shortname, function(err){
if (err) return reject(err);
resolve(true);
});
} else {
debug('webHook doesn\'t exists');
resolve(false);
}
}
}catch(e){
reject(e);
}
});
};
function _removeUrlFromShortname(self, shortname, url, callback){
try{
var obj = jsonfile.readFileSync(self.db);
var deleted = false;
var len = obj[shortname].length;
if (obj[shortname].indexOf(url) !== -1)
obj[shortname].splice(obj[shortname].indexOf(url), 1);
if (obj[shortname].length !== len) deleted = true;
// save it back to the DB
if (deleted){
jsonfile.writeFileSync(self.db, obj);
debug('url removed from existing shortname');
callback(undefined, deleted);
} else callback(undefined, deleted);
}catch(e){
callback(e, undefined);
}
var deleted = false
var len = obj[shortname].length
if (obj[shortname].indexOf(url) !== -1) {
obj[shortname].splice(obj[shortname].indexOf(url), 1)
}
if (obj[shortname].length !== len) deleted = true
// save it back to the DB
if (deleted) {
jsonfile.writeFileSync(self.db, obj)
debug('url removed from existing shortname')
callback(null, deleted)
} else callback(null, deleted)
} catch (e) {
callback(e, null)
}
}
function _removeShortname(self, shortname, callback){
try{
var obj = jsonfile.readFileSync(self.db);
delete obj[shortname];
// save it back to the DB
jsonfile.writeFileSync(self.db, obj);
debug('whole shortname urls removed');
callback(undefined);
}catch(e){
callback(e);
}
function _removeShortname (self, shortname, callback) {
try {
var obj = jsonfile.readFileSync(self.db)
delete obj[shortname]
// save it back to the DB
jsonfile.writeFileSync(self.db, obj)
debug('whole shortname urls removed')
callback(null)
} catch (e) {
callback(e)
}
}
// async method
WebHooks.prototype.getDB = function() {
// return the whole JSON DB file.
var self = this;
return new Promise(function(resolve, reject){
jsonfile.readFile(self.db, function(err, obj) {
if (err){
if (err.code === 'ENOENT') // file not found
reject('file not found');
else
reject(err);
}else{
// file exists
resolve(obj);
}
});
});
};
WebHooks.prototype.getDB = function () {
// return the whole JSON DB file.
var self = this
return new Promise(function (resolve, reject) {
jsonfile.readFile(self.db, function (err, obj) {
if (err) {
reject(err) // file not found
} else {
resolve(obj) // file exists
}
})
})
}
// async method
WebHooks.prototype.getWebHook = function(shortname) {
// return the selected WebHook.
var self = this;
return new Promise(function(resolve, reject){
jsonfile.readFile(self.db, function(err, obj) {
if (err){
if (err.code === 'ENOENT') // file not found
reject('file not found');
else
reject(err);
}else{
// file exists
if (obj[shortname])
resolve(obj[shortname]);
else
resolve({});
}
});
});
};
WebHooks.prototype.getWebHook = function (shortname) {
// return the selected WebHook.
var self = this
return new Promise(function (resolve, reject) {
jsonfile.readFile(self.db, function (err, obj) {
if (err) {
reject(err) // file not found
} else {
// file exists
if (obj[shortname]) {
resolve(obj[shortname])
} else {
resolve({})
}
}
})
})
}
WebHooks.prototype.get_functions = function(){
return _functions;
};
WebHooks.prototype.getListeners = function () {
return _functions
}
WebHooks.prototype.getEmitter = function(){
return this.emitter;
};
WebHooks.prototype.getEmitter = function () {
return this.emitter
}
module.exports = WebHooks;
module.exports = WebHooks
{
"name": "node-webhooks",
"version": "1.1.3",
"version": "1.1.4",
"description": "Create and trigger your own webHooks",
"main": "index.js",
"scripts": {
"test": "./node_modules/.bin/mocha --timeout=5000 test/**/*.js"
"test": "npm run std && npm run coverage && npm run security_check",
"std": "standard",
"coverage": "istanbul cover _mocha -- --timeout=5000 test/**/*.js",
"publish-coverage": "cat ./coverage/lcov.info | coveralls",
"security_check": "nsp check"
},

@@ -26,13 +30,23 @@ "repository": {

"dependencies": {
"bluebird": "^3.4.5",
"debug": "^2.2.0",
"eventemitter2": "^2.1.3",
"jsonfile": "^2.2.3",
"bluebird": "^3.5.0",
"debug": "^2.6.8",
"eventemitter2": "^4.1.0",
"jsonfile": "^3.0.0",
"lodash": "^4.15.0",
"request": "^2.69.0"
"request": "^2.81.0"
},
"devDependencies": {
"chai": "3.5.0",
"mocha": "1.21.4"
"chai": "^4.0.2",
"coveralls": "^2.11.16",
"istanbul": "^0.4.5",
"mocha": "^3.4.2",
"mocha-lcov-reporter": "^1.2.0",
"nsp": "^2.6.3",
"standard": "^10.0.2"
},
"standard": {
"env": [
"mocha"
]
}
}

@@ -1,5 +0,6 @@

# node-webhooks [![Build Status](https://travis-ci.org/roccomuso/node-webhooks.svg?branch=master)](https://travis-ci.org/roccomuso/node-webhooks) [![NPM Version](https://img.shields.io/npm/v/node-webhooks.svg)](https://www.npmjs.com/package/node-webhooks)
# node-webhooks [![Build Status](https://travis-ci.org/roccomuso/node-webhooks.svg?branch=master)](https://travis-ci.org/roccomuso/node-webhooks) [![NPM Version](https://img.shields.io/npm/v/node-webhooks.svg)](https://www.npmjs.com/package/node-webhooks) [![Coverage Status](https://coveralls.io/repos/github/roccomuso/node-webhooks/badge.svg?branch=master)](https://coveralls.io/github/roccomuso/node-webhooks?branch=master) [![bitHound Overall Score](https://www.bithound.io/github/roccomuso/node-webhooks/badges/score.svg)](https://www.bithound.io/github/roccomuso/node-webhooks) [![Dependency Status](https://david-dm.org/roccomuso/node-webhooks.png)](https://david-dm.org/roccomuso/node-webhooks)
=====================
[![Standard - JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
## What WebHooks are used for

@@ -29,3 +30,3 @@

// Initialize WebHooks module.
var WebHooks = require('node-webhooks');
var WebHooks = require('node-webhooks')

@@ -35,3 +36,3 @@

db: './webHooksDB.json', // json file that store webhook URLs
});
})

@@ -42,4 +43,4 @@ // sync instantation - add a new webhook called 'shortname1'

}).catch(function(err){
console.log(err);
});
console.log(err)
})

@@ -50,14 +51,14 @@ // add another webHook

}).catch(function(err){
console.log(err);
console.log(err)
});
// remove a single url attached to the given shortname
// webHooks.remove('shortname3', 'http://127.0.0.1:9000/query/').catch(function(err){console.error(err);});
// webHooks.remove('shortname3', 'http://127.0.0.1:9000/query/').catch(function(err){console.error(err);})
// if no url is provided, remove all the urls attached to the given shortname
// webHooks.remove('shortname3').catch(function(err){console.error(err);});
// webHooks.remove('shortname3').catch(function(err){console.error(err);})
// trigger a specific webHook
webHooks.trigger('shortname1', {data: 123});
webHooks.trigger('shortname2', {data: 123456}, {header: 'header'}); // payload will be sent as POST request with JSON body (Content-Type: application/json) and custom header
webHooks.trigger('shortname1', {data: 123})
webHooks.trigger('shortname2', {data: 123456}, {header: 'header'}) // payload will be sent as POST request with JSON body (Content-Type: application/json) and custom header

@@ -74,13 +75,13 @@ ```

DEBUG: true
});
})
var emitter = webHooks.getEmitter();
var emitter = webHooks.getEmitter()
emitter.on('*.success', function (shortname, statusCode, body) {
console.log('Success on trigger webHook' + shortname + 'with status code', statusCode, 'and body', body);
});
console.log('Success on trigger webHook' + shortname + 'with status code', statusCode, 'and body', body)
})
emitter.on('*.failure', function (shortname, statusCode, body) {
console.error('Error on trigger webHook' + shortname + 'with status code', statusCode, 'and body', body);
});
console.error('Error on trigger webHook' + shortname + 'with status code', statusCode, 'and body', body)
})
```

@@ -87,0 +88,0 @@

@@ -1,12 +0,12 @@

var chai = require('chai');
var expect = chai.expect;
var should = chai.should();
var debug = require('debug')('test-suite');
var http = require('http');
var fs = require('fs');
var path = require('path');
var WebHooks = require('../index');
var webHooks;
var emitter;
var DB_FILE = path.join(__dirname, './webHooksDB.json'); // json file that store webhook URLs
var chai = require('chai')
var expect = chai.expect
var should = chai.should()
var debug = require('debug')('test-suite')
var http = require('http')
var fs = require('fs')
var path = require('path')
var WebHooks = require('../index')
var webHooks
var emitter
var DB_FILE = path.join(__dirname, './webHooksDB.json') // json file that store webhook URLs

@@ -32,435 +32,475 @@ // IMPLEMENTED TESTS:

// instantiate a basic web server
var PORT = 8000;
var URI = 'http://127.0.0.1:' + PORT;
var PORT = 8000
var URI = 'http://127.0.0.1:' + PORT
var OUTCOMES = {};
var LOADTEST = 0;
var OUTCOMES = {}
var LOADTEST = 0
function handleRequest(request, response) {
debug('called method:', request.method);
debug('called URL:', request.url);
debug('headers:', request.headers);
var body = [];
request.on('data', function(chunk) {
body.push(chunk);
}).on('end', function() {
body = Buffer.concat(body).toString(); // as string
OUTCOMES[request.url] = {
headers: request.headers,
body: body
};
if (request.url.indexOf('/2/') !== -1) LOADTEST++;
debug('body:', body);
if (request.url.indexOf('/fail') !== -1)
response.writeHead(400, {'Content-Type': 'application/json'});
else
response.writeHead(200, {'Content-Type': 'application/json'});
response.end('Path Hit: ' + request.url);
function handleRequest (request, response) {
debug('called method:', request.method)
debug('called URL:', request.url)
debug('headers:', request.headers)
var body = []
request.on('data', function (chunk) {
body.push(chunk)
}).on('end', function () {
body = Buffer.concat(body).toString() // as string
OUTCOMES[request.url] = {
headers: request.headers,
body: body
}
if (request.url.indexOf('/2/') !== -1) LOADTEST++
debug('body:', body)
if (request.url.indexOf('/fail') !== -1) { response.writeHead(400, {'Content-Type': 'application/json'}) } else {
response.writeHead(200, {'Content-Type': 'application/json'})
}
response.end('Path Hit: ' + request.url)
})
}
});
// Create a server
var server = http.createServer(handleRequest)
}
describe('Tests >', function () {
before(function (done) {
// Lets start our server
server.listen(PORT, function () {
// Callback triggered when server is successfully listening. Hurray!
debug('Server listening on: http://localhost:%s', PORT)
done()
})
})
//Create a server
var server = http.createServer(handleRequest);
it('eventually delete old DB', function (done) {
try {
fs.unlinkSync(DB_FILE)
} catch (e) {}
done()
})
describe('Tests >', function() {
before(function(done) {
//Lets start our server
server.listen(PORT, function() {
//Callback triggered when server is successfully listening. Hurray!
debug('Server listening on: http://localhost:%s', PORT);
done();
});
it('create a node-webHooks istance', function (done) {
webHooks = new WebHooks({
db: DB_FILE
})
should.exist(webHooks)
webHooks.should.be.an('object')
done()
})
});
it('check wether the DB file exists or not', function (done) {
fs.stat(DB_FILE, function (err) {
should.not.exist(err)
done()
})
})
it('eventually delete old DB', function(done) {
try {
fs.unlinkSync(DB_FILE);
} catch (e) {}
done();
});
it('add: shortname required', function (done) {
try {
webHooks.add(null, URI + '/1/aaa').then(function () {
done('Error expected')
}).catch(function (err) {
throw new Error(err)
})
} catch (e) {
expect(e.message).to.equal('shortname required!')
done()
}
})
it('create a node-webHooks istance', function(done) {
webHooks = new WebHooks({
db: DB_FILE,
});
should.exist(webHooks);
webHooks.should.be.an('object');
done();
});
it('add: Url required', function (done) {
try {
webHooks.add('hei', null).then(function () {
done('Error expected')
}).catch(function (err) {
throw new Error(err)
})
} catch (e) {
expect(e.message).to.equal('Url must be a string')
done()
}
})
it('check wether the DB file exists or not', function(done) {
fs.stat(DB_FILE, function(err) {
should.not.exist(err);
done();
});
});
it('remove: shortname required', function (done) {
try {
webHooks.remove(null, 'hei').then(function () {
done('Error expected')
}).catch(function (err) {
throw new Error(err)
})
} catch (e) {
expect(e.message).to.equal('shortname required!')
done()
}
})
it('add a webHook called hook1', function(done) {
webHooks.add('hook1', URI + '/1/aaa').then(function() {
done();
}).catch(function(err) {
throw new Error(err);
});
});
it('getDB() file', function (done) {
webHooks.getDB().then(function (db) {
should.exist(db)
done()
}).catch(function (e) {
throw e
})
})
it('add a new URL to the webHook hook1', function(done) {
webHooks.add('hook1', URI + '/1/bbb').then(function() {
done();
}).catch(function(err) {
throw new Error(err);
});
});
it('add a webHook called hook1', function (done) {
webHooks.add('hook1', URI + '/1/aaa').then(function () {
done()
}).catch(function (err) {
throw new Error(err)
})
})
it('should get the webHook using the .getWebHook method', function(done) {
webHooks.getWebHook('hook1').then(function(obj) {
should.exist(obj);
expect(obj.length).to.equal(2);
expect(obj).to.have.members([URI + '/1/aaa', URI + '/1/bbb']);
done();
}).catch(function(err) {
throw new Error(err);
});
});
it('add a new URL to the webHook hook1', function (done) {
webHooks.add('hook1', URI + '/1/bbb').then(function () {
done()
}).catch(function (err) {
throw new Error(err)
})
})
it('should fire the webHook with no body or headers', function(done) {
this.timeout(3000);
webHooks.trigger('hook1');
setTimeout(function() {
debug('OUTCOME-1:', OUTCOMES);
should.exist(OUTCOMES['/1/aaa']);
should.exist(OUTCOMES['/1/bbb']);
expect(OUTCOMES['/1/aaa']).to.have.property('headers');
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('');
expect(OUTCOMES['/1/bbb']).to.have.property('headers');
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('');
done();
}, 1000);
});
it('should get the webHook using the .getWebHook method', function (done) {
webHooks.getWebHook('hook1').then(function (obj) {
should.exist(obj)
expect(obj.length).to.equal(2)
expect(obj).to.have.members([URI + '/1/aaa', URI + '/1/bbb'])
done()
}).catch(function (err) {
throw new Error(err)
})
})
it('should fire the webHook with custom body', function(done) {
this.timeout(3000);
OUTCOMES = {};
webHooks.trigger('hook1', {
hello: 'world'
});
setTimeout(function() {
debug('OUTCOME-2:', OUTCOMES);
should.exist(OUTCOMES['/1/aaa']);
should.exist(OUTCOMES['/1/bbb']);
expect(OUTCOMES['/1/aaa']).to.have.property('headers');
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('{"hello":"world"}');
expect(OUTCOMES['/1/bbb']).to.have.property('headers');
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('{"hello":"world"}');
done();
}, 1000);
});
it('should fire the webHook with no body or headers', function (done) {
this.timeout(3000)
webHooks.trigger('hook1')
setTimeout(function () {
debug('OUTCOME-1:', OUTCOMES)
should.exist(OUTCOMES['/1/aaa'])
should.exist(OUTCOMES['/1/bbb'])
expect(OUTCOMES['/1/aaa']).to.have.property('headers')
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('')
expect(OUTCOMES['/1/bbb']).to.have.property('headers')
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('')
done()
}, 1000)
})
it('should fire the webHook with custom headers', function(done) {
this.timeout(3000);
OUTCOMES = {};
webHooks.trigger('hook1', {}, {
hero: 'hulk'
});
setTimeout(function() {
debug('OUTCOME-3:', OUTCOMES);
should.exist(OUTCOMES['/1/aaa']);
should.exist(OUTCOMES['/1/bbb']);
expect(OUTCOMES['/1/aaa']).to.have.deep.property('headers.hero').equal('hulk');
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('{}');
expect(OUTCOMES['/1/bbb']).to.have.deep.property('headers.hero').equal('hulk');
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('{}');
done();
}, 1000);
});
it('should fire the webHook with custom body', function (done) {
this.timeout(3000)
OUTCOMES = {}
webHooks.trigger('hook1', {
hello: 'world'
})
setTimeout(function () {
debug('OUTCOME-2:', OUTCOMES)
should.exist(OUTCOMES['/1/aaa'])
should.exist(OUTCOMES['/1/bbb'])
expect(OUTCOMES['/1/aaa']).to.have.property('headers')
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('{"hello":"world"}')
expect(OUTCOMES['/1/bbb']).to.have.property('headers')
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('{"hello":"world"}')
done()
}, 1000)
})
it('should fire the webHook with both custom body and headers', function(done) {
this.timeout(3000);
OUTCOMES = {};
webHooks.trigger('hook1', {
hello: 'rocco'
}, {
hero: 'iron-man'
});
setTimeout(function() {
debug('OUTCOME-3:', OUTCOMES);
should.exist(OUTCOMES['/1/aaa']);
should.exist(OUTCOMES['/1/bbb']);
expect(OUTCOMES['/1/aaa']).to.have.deep.property('headers.hero').equal('iron-man');
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('{"hello":"rocco"}');
expect(OUTCOMES['/1/bbb']).to.have.deep.property('headers.hero').equal('iron-man');
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('{"hello":"rocco"}');
done();
}, 1000);
});
it('should fire the webHook with custom headers', function (done) {
this.timeout(3000)
OUTCOMES = {}
webHooks.trigger('hook1', {}, {
hero: 'hulk'
})
setTimeout(function () {
debug('OUTCOME-3:', OUTCOMES)
should.exist(OUTCOMES['/1/aaa'])
should.exist(OUTCOMES['/1/bbb'])
expect(OUTCOMES['/1/aaa']).to.have.nested.property('headers.hero').equal('hulk')
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('{}')
expect(OUTCOMES['/1/bbb']).to.have.nested.property('headers.hero').equal('hulk')
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('{}')
done()
}, 1000)
})
it('should delete a single webHook URL', function(done) {
webHooks.remove('hook1', URI + '/1/bbb').then(function(removed) {
expect(removed).to.equal(true);
done();
}).catch(function(err) {
done(err);
});
});
it('should fire the webHook with both custom body and headers', function (done) {
this.timeout(3000)
OUTCOMES = {}
webHooks.trigger('hook1', {
hello: 'rocco'
}, {
hero: 'iron-man'
})
setTimeout(function () {
debug('OUTCOME-3:', OUTCOMES)
should.exist(OUTCOMES['/1/aaa'])
should.exist(OUTCOMES['/1/bbb'])
expect(OUTCOMES['/1/aaa']).to.have.nested.property('headers.hero').equal('iron-man')
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('{"hello":"rocco"}')
expect(OUTCOMES['/1/bbb']).to.have.nested.property('headers.hero').equal('iron-man')
expect(OUTCOMES['/1/bbb']).to.have.property('body').equal('{"hello":"rocco"}')
done()
}, 1000)
})
it('should return false trying to delete a not existing webHook URL', function(done) {
webHooks.remove('hook1', URI + '/1/bbb').then(function(removed) {
expect(removed).to.equal(false);
done();
}).catch(function(err) {
done(err);
});
});
it('should delete a single webHook URL', function (done) {
webHooks.remove('hook1', URI + '/1/bbb').then(function (removed) {
expect(removed).to.equal(true)
done()
}).catch(function (err) {
done(err)
})
})
it('should return false trying to delete a not existing webHook', function(done) {
webHooks.remove('not-existing').then(function(removed) {
expect(removed).to.equal(false);
done();
}).catch(function(err) {
done(err);
});
});
it('should return false trying to delete a not existing webHook URL', function (done) {
webHooks.remove('hook1', URI + '/1/bbb').then(function (removed) {
expect(removed).to.equal(false)
done()
}).catch(function (err) {
done(err)
})
})
it('fire the webHook and make sure just one URL is called', function(done) {
OUTCOMES = {};
webHooks.trigger('hook1');
setTimeout(function() {
should.exist(OUTCOMES['/1/aaa']);
should.not.exist(OUTCOMES['/1/bbb']);
expect(OUTCOMES['/1/aaa']).to.have.property('headers');
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('');
done();
}, 1000);
});
it('should return false trying to delete a not existing webHook', function (done) {
webHooks.remove('not-existing').then(function (removed) {
expect(removed).to.equal(false)
done()
}).catch(function (err) {
done(err)
})
})
it('should delete an entire webHook', function(done) {
webHooks.remove('hook1').then(function(removed) {
expect(removed).to.equal(true);
done();
}).catch(function(err) {
done(err);
});
});
it('fire the webHook and make sure just one URL is called', function (done) {
OUTCOMES = {}
webHooks.trigger('hook1')
setTimeout(function () {
should.exist(OUTCOMES['/1/aaa'])
should.not.exist(OUTCOMES['/1/bbb'])
expect(OUTCOMES['/1/aaa']).to.have.property('headers')
expect(OUTCOMES['/1/aaa']).to.have.property('body').equal('')
done()
}, 1000)
})
it('should fire the deleted webHook and make sure no request is dispatched at all', function(done) {
OUTCOMES = {};
webHooks.trigger('hook1');
setTimeout(function() {
expect(OUTCOMES).to.deep.equal({});
should.not.exist(OUTCOMES['/1/aaa']);
should.not.exist(OUTCOMES['/1/bbb']);
done();
}, 1000);
});
it('should delete an entire webHook', function (done) {
webHooks.remove('hook1').then(function (removed) {
expect(removed).to.equal(true)
done()
}).catch(function (err) {
done(err)
})
})
it('should create a new webHook called hook2 for loadtest', function(done) {
webHooks.add('hook2', URI + '/2/aaa').then(
webHooks.add('hook2', URI + '/2/bbb').then(function() {
done();
it('should fire the deleted webHook and make sure no request is dispatched at all', function (done) {
OUTCOMES = {}
webHooks.trigger('hook1')
setTimeout(function () {
expect(OUTCOMES).to.deep.equal({})
should.not.exist(OUTCOMES['/1/aaa'])
should.not.exist(OUTCOMES['/1/bbb'])
done()
}, 1000)
})
it('should create a new webHook called hook2 for loadtest', function (done) {
webHooks.add('hook2', URI + '/2/aaa').then(
webHooks.add('hook2', URI + '/2/bbb').then(function () {
done()
})
).catch(function(err) {
throw new Error(err);
});
});
).catch(function (err) {
throw new Error(err)
})
})
it('check webHooks were saved successfully using the .getWebHook method', function(done) {
webHooks.getWebHook('hook2').then(function(obj) {
debug('hook2:', obj);
should.exist(obj);
expect(obj.length).to.equal(2);
expect(obj).to.have.members([URI + '/2/aaa', URI + '/2/bbb']);
done();
}).catch(function(err) {
throw new Error(err);
});
});
it('check webHooks were saved successfully using the .getWebHook method', function (done) {
webHooks.getWebHook('hook2').then(function (obj) {
debug('hook2:', obj)
should.exist(obj)
expect(obj.length).to.equal(2)
expect(obj).to.have.members([URI + '/2/aaa', URI + '/2/bbb'])
done()
}).catch(function (err) {
throw new Error(err)
})
})
it('should fire the webHook 1000 times and 2000 REST calls are expected', function(done) {
this.timeout(25 * 1000);
it('should fire the webHook 1000 times and 2000 REST calls are expected', function (done) {
this.timeout(25 * 1000)
// disabling debug to avoid console flooding
//debug = function() {};
// debug = function() {};
for (var i = 1; i <= 1000; i++)
(function(i) {
webHooks.trigger('hook2', {
i: i
});
})(i);
for (var i = 1; i <= 1000; i++) {
(function (i) {
webHooks.trigger('hook2', {
i: i
})
})(i)
}
var loop = setInterval(function() {
console.log('Got', LOADTEST + '/2000', 'REST calls');
if (LOADTEST === 2000){
clearInterval(loop);
done();
}
}, 500);
var loop = setInterval(function () {
console.log('Got', LOADTEST + '/2000', 'REST calls')
if (LOADTEST === 2000) {
clearInterval(loop)
done()
}
}, 500)
})
})
});
describe('Events >', function () {
it('Should get the emitter', function (done) {
emitter = webHooks.getEmitter() // get the emitter
should.exist(emitter)
done()
})
it('Should get all the listeners func.', function (done) {
should.exist(webHooks.getListeners()) // get the callbacks obj
done()
})
});
it('Should add a new Hook #3', function (done) {
webHooks.add('hook3', URI + '/3/aaa').then(function () {
done()
}).catch(function (err) {
throw new Error(err)
})
})
describe('Events >', function(){
it('Should get the emitter', function(done){
emitter = webHooks.getEmitter(); // get the emitter
should.exist(emitter);
done();
});
it('Should add a new Hook #3', function(done){
webHooks.add('hook3', URI + '/3/aaa').then(function() {
done();
}).catch(function(err) {
throw new Error(err);
});
});
it('Should catch a specific success event', function(done){
emitter.on('hook3.failure', function(shortname, stCode, body){
debug('hook3.failure:', shortname, stCode, body);
done('hook3.failure error: wrong event catched.');
});
emitter.on('hook3.success', function(shortname, statusCode, body){
debug('hook3.success:', {shortname: shortname, statusCode: statusCode, body: body});
should.exist(shortname);
should.exist(statusCode);
should.exist(body);
shortname.should.equal('hook3');
statusCode.should.equal(200);
body.should.equal('Path Hit: /3/aaa'); // body response from the server
done();
});
it('Should catch a specific success event', function (done) {
emitter.on('hook3.failure', function (shortname, stCode, body) {
debug('hook3.failure:', shortname, stCode, body)
done('hook3.failure error: wrong event catched.')
})
emitter.on('hook3.success', function (shortname, statusCode, body) {
debug('hook3.success:', {shortname: shortname, statusCode: statusCode, body: body})
should.exist(shortname)
should.exist(statusCode)
should.exist(body)
shortname.should.equal('hook3')
statusCode.should.equal(200)
body.should.equal('Path Hit: /3/aaa') // body response from the server
done()
})
// fire the hook
webHooks.trigger('hook3', {
header1: 'pippo'
}, {
prop1 : 'paperino'
});
webHooks.trigger('hook3', {
header1: 'pippo'
}, {
prop1: 'paperino'
})
})
});
it('Should remove the specific event listener and fire the hook', function (done) {
this.timeout(4000)
emitter.removeAllListeners('hook3')
emitter.on('hook3.success', function (s, st, body) {
debug('hook3.success error:', s, st, body)
done('error: removed listener should not be called!')
})
emitter.removeAllListeners('hook3')
webHooks.trigger('hook3')
setTimeout(function () {
done()
}, 2000)
})
it('Should remove the specific event listener and fire the hook', function(done){
this.timeout(4000);
emitter.removeAllListeners('hook3');
emitter.on('hook3.success', function(s, st, body){
debug('hook3.success error:', s, st, body);
done('error: removed listener should not be called!');
});
emitter.removeAllListeners('hook3');
webHooks.trigger('hook3');
setTimeout(function(){
done();
}, 2000);
});
it('add a failing webHook called hook4', function (done) {
webHooks.add('hook4', URI + '/4/fail').then(function () {
done()
}).catch(function (err) {
throw new Error(err)
})
})
it('add a failing webHook called hook4', function(done){
webHooks.add('hook4', URI + '/4/fail').then(function() {
done();
}).catch(function(err) {
throw new Error(err);
});
});
it('Should catch a specific failure event', function(done){
emitter.on('hook4.success', function(){
done('error: wrong event catched!');
});
emitter.on('hook4.failure', function(shortname, statusCode, body){
should.exist(shortname);
should.exist(statusCode);
should.exist(body);
shortname.should.equal('hook4');
statusCode.should.equal(400);
body.should.equal('Path Hit: /4/fail');
done();
});
it('Should catch a specific failure event', function (done) {
emitter.on('hook4.success', function () {
done('error: wrong event catched!')
})
emitter.on('hook4.failure', function (shortname, statusCode, body) {
should.exist(shortname)
should.exist(statusCode)
should.exist(body)
shortname.should.equal('hook4')
statusCode.should.equal(400)
body.should.equal('Path Hit: /4/fail')
done()
})
// fire the hook
webHooks.trigger('hook4', {
header1: 'foo'
}, {
prop2 : 'peterpan'
});
});
webHooks.trigger('hook4', {
header1: 'foo'
}, {
prop2: 'peterpan'
})
})
it('Should add new hooks for multiple events catch', function(done){
webHooks.add('hook5', URI + '/5/success').then(function() {
webHooks.add('hook6', URI + '/6/success').then(function() {
webHooks.add('hook7', URI + '/7/fail').then(function() {
webHooks.add('hook8', URI + '/8/fail').then(function() {
done();
});
});
});
}).catch(function(err) {
throw new Error(err);
});
});
it('Should add new hooks for multiple events catch', function (done) {
webHooks.add('hook5', URI + '/5/success').then(function () {
webHooks.add('hook6', URI + '/6/success').then(function () {
webHooks.add('hook7', URI + '/7/fail').then(function () {
webHooks.add('hook8', URI + '/8/fail').then(function () {
done()
})
})
})
}).catch(function (err) {
throw new Error(err)
})
})
it('Should catch all the success events', function(done){
var got = 0;
emitter.on('*.failure', function(shortname, stCode, body){
debug('error *.failure:', shortname, stCode, body);
done('*.failure error: wrong event catched.');
});
emitter.on('*.success', function(shortname, statusCode, body){
debug('captured events:', got);
should.exist(shortname);
should.exist(statusCode);
should.exist(body);
expect(shortname).to.be.oneOf(['hook5','hook6']);
statusCode.should.equal(200);
expect(body).to.be.oneOf(['Path Hit: /5/success', 'Path Hit: /6/success']);
++got;
if (got === 2){
emitter.removeAllListeners('*.success');
emitter.removeAllListeners('*.failure');
done();
}
});
it('Should catch all the success events', function (done) {
var got = 0
emitter.on('*.failure', function (shortname, stCode, body) {
debug('error *.failure:', shortname, stCode, body)
done('*.failure error: wrong event catched.')
})
emitter.on('*.success', function (shortname, statusCode, body) {
debug('captured events:', got)
should.exist(shortname)
should.exist(statusCode)
should.exist(body)
expect(shortname).to.be.oneOf(['hook5', 'hook6'])
statusCode.should.equal(200)
expect(body).to.be.oneOf(['Path Hit: /5/success', 'Path Hit: /6/success'])
++got
if (got === 2) {
emitter.removeAllListeners('*.success')
emitter.removeAllListeners('*.failure')
done()
}
})
// fire the hooks
webHooks.trigger('hook5');
webHooks.trigger('hook6');
});
webHooks.trigger('hook5')
webHooks.trigger('hook6')
})
it('Should catch all the failure events', function(done){
var got = 0;
emitter.on('*.success', function(shortname, stCode, body){
debug('error *.success:', shortname, stCode, body);
done('*.success error: wrong event catched.');
});
emitter.on('*.failure', function(shortname, statusCode, body){
debug('captured events:', got);
should.exist(shortname);
should.exist(statusCode);
should.exist(body);
expect(shortname).to.be.oneOf(['hook7','hook8']);
statusCode.should.equal(400);
expect(body).to.be.oneOf(['Path Hit: /7/fail', 'Path Hit: /8/fail']);
++got;
if (got === 2){
emitter.removeAllListeners('*.success');
emitter.removeAllListeners('*.failure');
done();
}
});
it('Should catch all the failure events', function (done) {
var got = 0
emitter.on('*.success', function (shortname, stCode, body) {
debug('error *.success:', shortname, stCode, body)
done('*.success error: wrong event catched.')
})
emitter.on('*.failure', function (shortname, statusCode, body) {
debug('captured events:', got)
should.exist(shortname)
should.exist(statusCode)
should.exist(body)
expect(shortname).to.be.oneOf(['hook7', 'hook8'])
statusCode.should.equal(400)
expect(body).to.be.oneOf(['Path Hit: /7/fail', 'Path Hit: /8/fail'])
++got
if (got === 2) {
emitter.removeAllListeners('*.success')
emitter.removeAllListeners('*.failure')
done()
}
})
// fire the hooks
webHooks.trigger('hook7');
webHooks.trigger('hook8');
});
webHooks.trigger('hook7')
webHooks.trigger('hook8')
})
after(function(done) {
after(function (done) {
// stop the server
server.close(function() {
done();
});
});
});
server.close(function () {
done()
})
})
})

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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