Introduction
Plugins for stash-it are things that:
- alter / extend how current cache instance's methods work
- add new functionality to cache instance
A plugin is an object that consists of, at least, one property: hooks
and / or getExtensions
. Here is an example of full grown plugin (without the body):
{
hooks: [],
getExtensions: (cacheInstance) => {}
}
How to use a plugin? What do I get from it?
If you take for example stash-it-plugin-debug you gain two things (read more on this plugin's repo page):
- Data that flows in, through and out of each cache's method is going to be tracked (using passed callback, e.g.
console.log
). - Adds new method
runDiangnostics()
.
Here's how you use it:
import { registerPlugins } from 'stash-it';
import createDebugPlugin from 'stash-it-plugin-debug';
// assuming that you already have cache instance
const cacheWithPlugins = registerPlugins(cacheInstance, [ createDebugPlugin(console.log) ]);
cacheWithPlugins.runDiagnostics(); // without the plugin, this method would not be here
And that's it.
Using various plugins you can extend your cache instance to whatever combination you desire.
Take a look at registerPlugins API docs, as it will explain a bit more how registering plugins works, how you can register more plugins etc.
Can I register more than one plugin? Or the same plugin many times?
Plugins, in general, can be registered multiple times (different ones) for given cache instance. For instance:
const cacheWithPlugins = registerPlugins(cache, [ some, plugins ]);
// you can further add plugins to newly created object
const cacheWithEvenMorePlugins = registerPlugins(cacheWithPlugins, [ other, ones ]);
But, if you try to register plugins, which extend cache with methods (their names) that already exist, it will throw. For instance, if you try to register getHandlersPlugin twice:
registerPlugins(cache, [ debugPlugin, debugPlugin ]);
// or this way:
const cacheWithPlugins = registerPlugins(cache, [ debugPlugin ]);
const cacheWithMorePlugins = registerPlugins(cacheWithPlugins, [ debugPlugin ]);
// Both of them will throw trying to add a method that already exists.
Why? This precaution is added to prevent overwriting existing methods (especially the base ones).