Skip to main content

Cache

The cache module handling various ways to store data in the browser.

The curent cache system implements Local Storage Cache.

By default there is a Cache Manager that manauges the caching behind the scenes.

Examples#

Setting a key/value

import cache from 'mongez/cache';
cache.set('name', 'Hasan'); // setting a key named `name` with value `Hasan`

Getting a value for the given key

import cache from 'mongez/cache';
console.log(cache.get('name')); // Hasan

Getting a default value if the given key does not exist

import cache from 'mongez/cache';
console.log(cache.get('someKey', 'otherValue')); // otherValue

Removing key from the cache

import cache from 'mongez/cache';
cache.remove('name');

The imported cache object from mongez/cache is an instance of Cache Manager;

Default Cache Driver#

At the time being, the current default cache driver is Plain Local Storage, which is being handled by Cache Manager.

Cache Drivers List#

The following list implements Cache Driver Interface.

You can directly call the driver from the cache by the following example:


import { EncrypredLocalStorage } from 'mongez/cache';

Cache Driver Interface#

interface CacheDriverInterface {    /**     * Set cache into storage     * @param {string} key      * @param {any} value      */    set(key: string, value: any): void;    /**     * Get value from cache engine, if key does not exist return default value     * @param {string} key      * @param {any} defaultValue       */    get(key: string, defaultValue: any): any;    /**     * Remove the given key from the cache storage     *      * @param  {string} key     */    remove(key: string): void;}

Cache Key Prefix#

It's prefered to set a key prefix that will be added to every key stored in cache engine for the current application.

shared/config.ts
import config, { ConfigList } from 'mongez/config';
const settings: ConfigList = {    // global configurations here    cache: {        prefix: 'mngz-'    }};
config.set(settings);

Once the prefix is set, any stored key will be prefixed with mngz-

For example:

import cache from 'mongez/cache';
cache.set('name', 'Hasan'); // key: mngz-name, value: Hasan

but you can get your keys values normally:

import cache from 'mongez/cache';
cache.get('name'); // Hasan

The get method will automatically add the key prefix for you so you don't need to do it yourself.