All Projects → sebelga → promised-hooks

sebelga / promised-hooks

Licence: MIT license
Middleware utility for your Promises

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to promised-hooks

alls
Just another library with the sole purpose of waiting till all promises to complete. Nothing more, Nothing less.
Stars: ✭ 13 (-48%)
Mutual labels:  promise, promise-library
retryx
Promise-based retry workflow library.
Stars: ✭ 21 (-16%)
Mutual labels:  promise, promise-library
nancy
How JavaScript Promise Works
Stars: ✭ 26 (+4%)
Mutual labels:  promise, promise-library
Promise Fun
Promise packages, patterns, chat, and tutorials
Stars: ✭ 3,779 (+15016%)
Mutual labels:  promise, promise-library
buzy
Async queue manager for node and browser
Stars: ✭ 23 (-8%)
Mutual labels:  promise, promise-library
Jdeferred
Java Deferred/Promise library similar to JQuery.
Stars: ✭ 1,483 (+5832%)
Mutual labels:  promise, promise-library
React Organism
Dead simple React state management to bring pure components alive
Stars: ✭ 219 (+776%)
Mutual labels:  promise
Await Of
await wrapper for easier errors handling without try-catch
Stars: ✭ 240 (+860%)
Mutual labels:  promise
Promisejs.org
a promise website to document and promote
Stars: ✭ 210 (+740%)
Mutual labels:  promise
Limitrr
Light NodeJS rate limiting and response delaying using Redis - including Express middleware.
Stars: ✭ 203 (+712%)
Mutual labels:  promise
promise4j
Fluent promise framework for Java
Stars: ✭ 20 (-20%)
Mutual labels:  promise
When
⏰ A lightweight implementation of Promises in Swift
Stars: ✭ 250 (+900%)
Mutual labels:  promise
Api
Promise and RxJS APIs around Polkadot and any Substrate-based chain RPC calls. It is dynamically generated based on what the Substrate runtime provides in terms of metadata. Full documentation & examples available
Stars: ✭ 232 (+828%)
Mutual labels:  promise
Luch Request
luch-request 是一个基于Promise 开发的uni-app跨平台、项目级别的请求库,它有更小的体积,易用的api,方便简单的自定义能力。
Stars: ✭ 219 (+776%)
Mutual labels:  promise
Spirit
Modern modular library for building web applications
Stars: ✭ 241 (+864%)
Mutual labels:  promise
Tickedoff
Tiny library (<200B gzip) for deferring something by a "tick"
Stars: ✭ 213 (+752%)
Mutual labels:  promise
Axios
Promise based HTTP client for the browser and node.js
Stars: ✭ 89,857 (+359328%)
Mutual labels:  promise
Promise Queue
Promise-based queue
Stars: ✭ 210 (+740%)
Mutual labels:  promise
Massive Js
A data mapper for Node.js and PostgreSQL.
Stars: ✭ 2,521 (+9984%)
Mutual labels:  promise
Escape From Callback Mountain
Example Project & Guide for mastering Promises in Node/JavaScript. Feat. proposed 'Functional River' pattern
Stars: ✭ 249 (+896%)
Mutual labels:  promise

Middleware utility for your Promises

NPM Version Build Status coveralls-image Commitizen friendly

Add pre and post middleware hooks to any function returning a Promise.
Read the post on Medium for some example.

Install

yarn add promised-hooks
# or
npm install promised-hooks --save`

Warp your Class/function/object

In order to add "pre" and "post" hooks to your promise you need to wrap their containing object (Class/function/object)

const hooks = require('promised-hooks');

// Class
class User {
    // some method that returns a Promise
    someMethod() { ... }
}

// Function
function User() {
}
User.prototype.someMethod = function someMethod() { ... }

// Object
const api = {
    save: function() { ... }
};

// Wrap them to add "pre" and "post" hooks functionalities to their methods
hooks.wrap(User);
hooks.wrap(api);

Add middleware

pre() method

Adds a middelware to a promise that will be resolved or rejected before the method you are targetting. If the middelware rejects the Promise the original method is not executed. All the parameters sent to the original methods are available in the arguments of your middleware.

const hooks = require('promised-hooks');

class User {
	// instance methods
    save() { ... }

	// works also with static methods
    static otherMethod() { ... }
}

hooks.wrap(User);

User.pre('save', doSometingBeforeSaving);

function doSometingBeforeSaving()  {
    // Access the arguments passed if needed
    const args = Array.prototype.slice.apply(arguments);

    // the scope (this) is the original Object wrapped

    // return a Promise
    return new Promise((resolve, reject) => {

        // ... do some async stuff

        // then resolve or reject
        resolve();
    });
}

Override

You can override the original arguments sent to the target method by resolving the middleware with an object containing an "__override" property.

User.pre('save', doSometingBeforeSaving);

function doSometingBeforeSaving()  {
	return new Promise((resolve, reject) => {
        // ...

        resolve({ __override: 123 }); // single argument
        // or
        resolve({ __override: [ 123, 'arg2' ] }); // multi arguments
    });

    /**
     * With the above override, the User.save() method will
     * receive those arguments instead of the one originally provided
     */
}

post() method

Adds a middelware to be executed after the method you are targetting has been resolved. If the post middleware fails and rejects the Promise, the original Promise still resolves and the "post" errors are added the response (see below).

If you resolve your post middelware with an object containing an "__override" property (same as with "pre" hook), it will override the original response.

const hooks = require('promised-hooks');

class User {
	// instance methods
	save() { ... }

	// works also with static (prototype) methods
	static otherMethod() { ... }
}

hooks.wrap(User);

// Several middleware can be added at once with an Array
User.post('save', [postMiddleware1, postMiddleware2]);

function postMiddleware1(data) {
    // data is the resolved value from the original promised method
    // or previous "post" hooks with an __override property

    // do some async stuff ...

    // and resolve a Promise
    return Promise.resolve();

    // If needed, you can override the response
    return Promise.resolve({ __override: 'my new response' });
}

function postMiddleware2(data) {
    return new Promise((resolve, reject) => {
        // call async service...
        myApi.doSomething((err) => {
            if (err) {
                /* if the async fails you would then reject your promise.
                 * The original response is *not* overriden
                 * (see errors in "post" hook below)
                 */
                return reject(err);
            }

            // no error
            return resolve();
        });
    });
}

Errors in "post" hooks

If one of the "post" hook fails and rejects its Promise then a Symbol is added on the response containing an Array with the errors. If the response is a primitive('string', 'number', boolean) then it is first converted to an object with a "result" property.

// For example, if the response returned by the targeted method is:
'my response'

// in case there are "post" hooks error it will be converted to:
{
    result: 'my response'
}

You access the errors Array with the hooks.ERRORS Symbol.

const hooks = require('promised-hooks');

class User {
	save() { ... }
}

hooks.wrap(User);

User.post('save', postMiddleware);

function postMiddleware() {
    return new Promise((resolve, reject) => {
    	// call async service...
    	myApi.doSomething((err) => {
            if (err) {
                return reject(err);
            }
            return resolve();
    	});
    });
}

// Somewhere else in your code

const user = new User();

user.save().then((response) => {
    // The save occurred without issue but
    // let's check for any "post" hook error
    if (response[hooks.ERRORS]) {
        // deal with errors
    }
    ...
});

Scope (this)

The scope (this) of the middelware is set by default on the "wrapped" object. If you need to change it at runtime, you can declare a __scopeHook function on the object that will be called for each hook. This method, when called, receives 3 parameters:

  • the target method
  • the arguments (array of arguments sent to the targeted method)
  • the hook method name
class User {
    save() {}

    __scopeHook(targetMethod, args, hookMethod) {
        console.log(targetMethod); // "save"
        console.log(args); // [123]
        console.log(hookMethod); // "hashPassword"

        // You can here return any object for the scope

        if (hookMethod === 'hashPassword') {
            return { x: 'abc' }; // set the scope
        }

        // If you return "undefined" the scope is not changed
        return undefined;
    }
}
hooks.wrap(User);

User.pre('save', function hashPassword() {
    // Check the scope
    console.log(this); // { x: 'abc' }
});

// ...

const user = new User();
user.save(123).then( ... );

Example

const hooks = require('promised-hooks');

class User {
    save(userData) {
        return new Promise((resolve, reject) {
            // ...your logic to save a user then
            resolve(response);
        });
    }

    // works also on static methods
    static otherMethod() { ... }
}

// Wrap the class to add hooks functionalities
hooks.wrap(User);

// Hash a user password before saving
User.pre('save', (userData) => {
    /**
     * INFO: If you need to access the User class from this middelware
     * you can not use an arrow function as the scope is lost.
     * Use a normal function and *this* will be your Class
    */

    if (typeof userData.password !== 'undefined') {
        userData.password = hashString(userData.password);
    }

    return Promise.resolve();

    // ----------

    function hashString(str) {
        // ... logic to hash a string
        return hashedString;
    }
});

// Let's email our newly created user
User.post('save', (response) => {
    // response is what the target method returns
    const email = response.email;

    // Return a method that returns a Promise
    return yourMailService.sendEmail(email);
});

// Create new user
const user = new User();

// Save user
user.save({ name: 'John', password: 'snow' })
    .then((response) => {
        // Save success

        // Check if there are any errors in our "post" middleware
        if (response.[hooks.ERRORS]) {
            // deal with Post hook error
        }

    }, (err) => {
        // Save failed
    });

Credits

I have been inspired by the hooks-fixed library from @vkarpov15 to write this small utility.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].