DEV Community

Michael Di Prisco
Michael Di Prisco

Posted on

Our Journey In The Open Source World - cache-candidate-plugin-invalidate-function

Do you know we built an awesome caching library for Node at Jointly? No?! Well, check this out!

Today we want to present you our second plugin: A plugin providing an invalidation mechanism to the cache-candidate!

What is this?

This is a plugin for @jointly/cache-candidate providing an invalidation mechanism under specific conditions.

How To Install?

$ npm install @jointly/cache-candidate-plugin-invalidate-function
Enter fullscreen mode Exit fullscreen mode

How To Use It?

The library exposes a PluginInvalidateFunction object that can be used as a plugin for the cacheCandidate library.

import { cacheCandidate } from '@jointly/cache-candidate';
import { PluginInvalidateFunction } from '@jointly/cache-candidate-plugin-invalidate-function';

async function getUsers(filters) {
  // Do something
  return users;
}

const cachedGetUsers = cacheCandidate(getUsers, {
  requestsThreshold: 1,
  plugins: [
      {
        name: PluginInvalidateFunction.name,
        hooks: PluginInvalidateFunction.hooks,
        // ...PluginInvalidateFunction would do the same
        additionalParameters: { invalidateFunction: (fnArgs) => {
          let shouldInvalidate = executeQueryToDetermineIfCacheShouldBeInvalidated();
          return shouldInvalidate;
        } } // <-- This will invalidate the cache record if the amount of filters passed to the method is greater than 1
      }
    ]
});

let users;
users = await cachedGetUsers(); // <-- This will be executed and cached.
// Here something happens so that executeQueryToDetermineIfCacheShouldBeInvalidated returns true
users = await cachedGetUsers(); // <-- This will be firstly invalidated, then executed and cached again.
Enter fullscreen mode Exit fullscreen mode

You must pass an additional parameter invalidateFunction property which instructs the plugin about when to invalidate the cache record.
This property must be a synchronous function (We have an open issue for it to go both sync and async, so it could change when this post will go live) that receives the arguments passed to the method on which the cacheCandidate operates and returns a boolean value.

If the function returns true, the cache record will be invalidated and the cacheCandidate will continue its normal execution.

Top comments (0)