Skip to main content

What is the Cache Manager

The Cache Manager is a higher level of working with the current cache engine that you set in the project configuration.

It has the same exact Cache Driver Interface alongside with two extra methods: setDriver and getDriver, these methods allow you to update/get current driver on runtime or event after certain critera.

Usage#

As demonstrated in the Introduction section, the default import of mongez/cache is an instance of CacheManager class.

Setting Value to current driver#

import cache from 'mongez/cache';
// store value in the current storage driver
cache.set('name', 'Hasan'); // set a name to Hasan with no return.

Getting Value from current driver#

import cache from 'mongez/cache';
// Get value from the current driver for the given 
cache.get('name'); // Hasan

Getting value from the current driver, or default value if key not exists#

import cache from 'mongez/cache';
// Get value from the current driver for the given, if not exists, return the default value which is 15 in our case
cache.get('someKey', 15); // 15

Removing key from the current driver#

import cache from 'mongez/cache';
// Removing key from cachecache.remove('name');
cache.get('name'); // null

Setting another driver#

By default current driver that is used in the cache manager is the one is set in the Cache configuration, if not set then it is the Plain Local Storage Driver.

But if updating current driver may be necessary in some point, it can be updated through setDriver method.

import cache, { CacheDriverInterface, EncryptedLocalStorageDriver } from 'mongez/cache';
const encrypedDriver: CacheDriverInterface = new EncryptedLocalStorageDriver();
cache.setDriver(encrypedDriver);

From being in that point, now all data will be encrypted when stored in the local storage.

Getting curent driver#

To get current driver instance, use the getDriver method.

import cache, { PlainLocalStorageDriver, CacheDriverInterface, EncryptedLocalStorageDriver } from 'mongez/cache';
// The PlainLocalStorageDriver is the default driverconsole.log(cache.getDriver() instanceof PlainLocalStorageDriver); // true 
const encrypedDriver: CacheDriverInterface = new EncryptedLocalStorageDriver();
cache.setDriver(encrypedDriver);
console.log(cache.getDriver() instanceof EncryptedLocalStorageDriver); // true