createExtensions

createExtensions is a method, which takes an object as a parameter. That object contains, cacheInstance, getPreData and getPostData. createExtensions returns an object with new method - one which will extend the cache instance. Passed cacheInstance / getPreData / getPostData can, but not necessarily must, be used.

Example without the use of cacheInstance

createExtensions: () => {
    return {
        logTimestamp: () => {
            const date = new Date();

            // logger was passed as an argument when plugin was created
            logger.log(date.toUTCString());
        }
    }
}

Once cache instance has a plugin registered with this method, it can be used like so:

cache.logTimestamp(); // this will log UTC string date

Example with the use of cacheInstance

createExtensions: ({ cacheInstance }) => {
    return {
        getItems: (keys) => {
            return keys.map(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:

cache.getItems([ 'foo', 'bar', 'keyForItemThatDoesNotExist' ]);
// [ itemFoo, itemBar, undefined ]

What about lifecycle of such created methods?

If you need them - you must add them. For that you will need getPreData and getPostData methods passed to createExtensions.

Here's how it would look like for getItems method, created in the previous example:

createExtensions: ({ cacheInstance, getPreData, getPostData }) => {
    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; 
        }
    }
}

Now getItems method is ready for preGetItems and postGetItems events. 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, prefixed by pre and post);

  • what properties are passed in the object (2nd argument to getPreData and getPostData);

  • what should be returned by each method (getPreData and getPostData);

  • 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.

Last updated