interceptable
Easily intercept calls to function properties
✨ ✨
Introduction
With this module, you can intercept calls to function properties on an object
- You hook in before and/or after a function is called
- Both sync and async function calls are interceptable
Installation
$ npm install interceptable --save
Demo's
Intercept synchronous functions that return a value (sync / success)
const interceptable = require('interceptable');
const obj = {
sayHello(name) {
console.log('... inside sayHello');
return `Hello ${name}!`;
}
};
const interceptor = ({ fn, args }) => {
console.log(`BEFORE call to ${fn} with args ${args}`);
return {
onSuccess(result) {
console.log(`AFTER call to ${fn} with args ${args} -> result: ${result}`);
},
};
};
const interceptableObj = interceptable(obj, interceptor);
interceptableObj.sayHello('Sam');
Intercept synchronous functions that throw an error (sync / error)
const interceptable = require('interceptable');
const obj = {
sayHello(name) {
console.log('... inside sayHello');
throw new Error(`Cannot say hello to ${name}!`);
}
};
const interceptor = ({ fn, args }) => {
console.log(`BEFORE call to ${fn} with args ${args}`);
return {
onError(err) {
console.log(`AFTER call to ${fn} with args ${args} -> error: ${err.message}`);
},
};
};
const interceptableObj = interceptable(obj, interceptor);
interceptableObj.sayHello('Sam');
Intercept asynchronous functions that resolve a value (async / success)
const interceptable = require('interceptable');
const obj = {
sayHello(name) {
console.log('... inside sayHello');
return Promise.resolve(`Hello ${name}!`);
}
};
const interceptor = ({ fn, args }) => {
console.log(`BEFORE call to ${fn} with args ${args}`);
return {
onSuccess(result) {
console.log(`AFTER call to ${fn} with args ${args} -> result: ${result}`);
},
};
};
const interceptableObj = interceptable(obj, interceptor);
interceptableObj.sayHello('Sam');
Intercept asynchronous functions that rejects an error (async / error)
const interceptable = require('interceptable');
const obj = {
sayHello(name) {
console.log('... inside sayHello');
return Promise.reject(new Error(`Cannot say hello to ${name}!`));
}
};
const interceptor = ({ fn, args }) => {
console.log(`BEFORE call to ${fn} with args ${args}`);
return {
onError(result) {
console.log(`AFTER call to ${fn} with args ${args} -> result: ${result}`);
},
};
};
const interceptableObj = interceptable(obj, interceptor);
interceptableObj.sayHello('Sam');