Library to bind pre and post hooks to functions. Often used to wrap a method before and after making a query to a database such as Mongodb.
Install the package.
$ npm install mustad -s
OR
$ yarn add mustad
You can either wrap an existing class/api or manually bind your hooks.
Take for example a simple API that does some work with a database.
import { wrap } from 'mustad';
import db from './db'; // fake Mongodb import.
const _api = {
async findUser(queryOrId, options) {
const user = await db.collection('user').findOne(queryOrId, options);
return user;
}
};
const api = wrap(_api);
api.pre('findUser', (next, queryOrId, options) => {
if (typeof queryOrId !== 'object')
queryOrId = { _id: queryOrId } // convert user ObjectId to query object.
next(null, queryOrId); // Mustad will append the missing "options" param if missing.
});
You can also implement Mustad manually and use in a class.
import { Mustad } from 'mustad';
class MyClass {
constructor() {
this._mustad = new Mustad(this);
}
findUser(queryOrId, options) {
// call database to find user.
}
// You might do it this way to limit binding
// to say only a few methods in your class.
// rather than allowing any method to be bound.
pre(type, handler) {
// type here might be "update" for example so
// you abtract away here so that you can bind
// to multiple methods with the user only supplying
// one keyword.
if (type === 'update')
this._mustad.pre(['update', 'updateOne', 'findOneAndUpdate'], handler);
return this;
}
}
const myClass = new MyClass();
Below are a couple common use case examples.
One each call of the next callback handler arguments are synchornized at position. New arguments are also appended to the chain so as to be available in the next hook.
For example calling next()
will provide all args as previously supplied. If you have two arguments after the next handler but you only override the first, next(null, newFirst)
the next hook will see args = [newFirst, oldSecond]
. If you add a new third argument the next hook in the chain will see all three arguments as show below:
api.pre('findUser', (next, queryOrId, options) => {
const meta = { timestamp: Date.now() };
next(null, queryOrId, options, meta); // meta now avail in next hook!!!
});
Say you want to log something but don't want to block in your hook by calling next(true)
we tell Mustad to proceed to the next hook without waiting. Finally we call next again with our typical options and Mustad will wrap everything up and then call our bound handler from our class or api.
api.pre('findUser', (next, queryOrId, options) => {
setTimeout(() => {
console.log('Next hook won\'t wait for me, but I will finish before calling api.findUser()');
next(); // this is the same as next(null, queryOrId, options)
});
next(true); // "true" tells Mustad to iterate to next hook.
});
Mustad fully supports promises. To use a promise simply do whatever you like in your hook and return the promise. Mustad will just figure it all out for you.
api.pre('findUser', (next, queryOrId, options) => {
return new Promise((resolve, reject) => {
// do some task resolve or reject.
if (false)
return reject('some rejection');
resolve('your_data');
})
});
Hooks allow you to either return values and then handle as needed or you can callback as we've shown with our next()
callback. Here are the options when returning a value or calling the next callback.
Action | Description |
---|---|
return true; | same as calling next() |
return false; | same as calling next(new Error(`Hook "findUser" returned false and exited.`)) |
return Promise.resolve(); | waits for promise then runs next hook. |
return undefined; | no action taken |
Action | Description |
---|---|
next() | same as calling next(null, ...args) where "args" are the original spread args. |
next(true) | won't wait causes next hook to be called but will finish before calling primary handler. |
next(false) | same as calling next(new Error(`Hook "findUser" returned false and exited.`)) |
next(new Error()) | will halt and exit all hooks. |
next(null, arg1) | calls next hook any args by index missing will be added to arg1 |
Property | Description | Default |
---|---|---|
enablePre | when enabled "pre" hooks are run | true |
enablePost | when enabled "post" hooks are run | true |
timeout | how long to wait for async hooks before continue | 3000 |
timeoutError | when timeout is elapsed whether to error or not | true |
include | array of methods to allow binding to undefined or [] is all | [] |
exclude | array of methods to allow PREVENT binding to | [] |
lazy | lazy mode binds hook wrapper automatically to any defined hook * | true |
pre(); post(); preExec(); postExec()
merely adds it to the internal collection as a hook. Lazy mode then ensures the defined handler name is wrapped so that it can handle calling these defined hooks. So by setting lazy to false you would then need to do the following manually:// Name - the name of the method
// handler - the prototype function itself.
// context - the optional context to bind to the hooks.
mustad.hook(name, handler, context);
If you need to do this manually it will be obvious. Additionally Mustad will check if the handler has already been wrapped.
See https://blujedis.github.io/mustad/
See CHANGE.md
See LICENSE.md
Generated using TypeDoc