getExtensions
getExtensions
is a method, which takes one parameter, cacheInstance, and returns an object with new method. Passed cacheInstance can but not necessarily must be used.
Example without the use of cacheInstance:
getExtensions: () => {
return {
logTimestamp: (logger) => {
const date = new Date();
logger.log(date.toUTCString());
}
}
}
Once cache instance has a plugin registered with this method, it can be used like so:
// providing that this plugin was registered
cache.logTimestamp(console); // this will run console.log with UTC string date
Example with the use of passed cacheInstance:
getExtensions: (cacheInstance) => {
return {
getItems: (keys) => {
return keys.forEach(cacheInstance.getItem);
}
}
}
Above method, getItems
, when passed an array of keys to it, will return an array of items (if found). Usage will look like this:
// providing that this plugin was registered
cache.getItems([ 'foo', 'bar', 'keyForItemThatDoesNotExist' ]); // [ itemFoo, itemBar, undefined ]
What about lifecycle of such created methods?
Well, you need to add them. For that you will need getPreData
and getPostData
methods available in stash-it
.
Here's how it would look like for getItems
method we created in previous example:
import { getPreData, getPostData } from 'stash-it';
// excerpt of given plugin, hence only getExtensions here
getExtensions: (cacheInstance) => {
return {
getItems: (keys) => {
const preData = getPreData('getItems', { keys, cacheInstance });
const items = preData.keys.map(cacheInstance.getItem);
const postData = getPostData('getItems', { keys: preData.keys, items, cacheInstance: preData.cacheInstance });
return postData.items;
}
}
}
And that's it. Your new method is ready for events preGetItems
and postGetItems
. If you would be a creator of such a plugin, your responsibility is to provide detailed information how lifecycle of such a method looks like:
- what event names are here (by convention it's the same as created method's name, plus prefixes);
- what properties are passed in 2nd argument to
getPreData
andgetPostData
; - what should be returned by each method (
getPreData
andgetPostData
); - what is returned by newly created method - here
getItems
.
Now, this method should have some data validation etc. but this is not the case of this example.
For more information how a complete plugin should look like, head straight to writing plugins.