Skip to content

Class: HybridWebCache

Represents a hybrid web cache that supports both asynchronous and synchronous operations for storing, retrieving, and managing key-value pairs with optional time-to-live (TTL) settings.

The cache can automatically remove expired entries and supports various storage engines.

Provides methods for setting, getting, checking existence, and unsetting values, as well as resetting the cache with new data. Includes utility functions for converting TTL and calculating storage size.

Author

Heliomar Marques

Examples

Basic Usage with Default Options (storage: Auto, ttl: 1 hour)

ts
import { HybridWebCache, StorageEngine } from 'hybrid-webcache';

const cache = new HybridWebCache();

await cache.set('sessionToken', 'abc123');
const tokenData = await cache.get<string>('sessionToken');
console.log(`Token: ${tokenData?.value}`); // Output: Token: abc123
console.log(`Is Expired: ${tokenData?.isExpired}`); // Output: Is Expired: false

Creating an instance with custom options (e.g., IndexedDB, 10-minute TTL)

ts
import { HybridWebCache, StorageEngine } from 'hybrid-webcache';

// Note: For IndexedDB, remember to call .init() if you plan to use synchronous methods
const indexedDBCache = new HybridWebCache('myAppCache', {
  storage: StorageEngine.IndexedDB,
  ttl: { minutes: 10 },
  removeExpired: true,
});

await indexedDBCache.init(); // Initialize IndexedDB to load memory cache for sync operations
//Setting and Getting Nested Data
await indexedDBCache.set('user.profile.firstName', 'John', { hours: 1 });
indexedDBCache.setSync('user.profile.lastName', 'Doe'); // Uses instance's default TTL (10 minutes)
indexedDBCache.setSync(['user', 'profile', 'age'], 30); // Array KeyPath

const userData = await indexedDBCache.get('user.profile');
console.log(userData?.value); // Output: { firstName: 'John', lastName: 'Doe', age: 30 }
const firstNameData = indexedDBCache.getSync('user.profile.firstName');
console.log(firstNameData?.value); // Output: John

// Checking for Key Existence
const hasUser = await indexedDBCache.has('user.profile.firstName');
console.log(`Has user first name: ${hasUser}`); // Output: Has user first name: true

const hasNonExistentKey = indexedDBCache.hasSync('non.existent.key');
console.log(`Has non-existent key: ${hasNonExistentKey}`); // Output: Has non-existent key: false

// Unsetting Data (Partial and Full)
const complexObject = {
  theme: 'dark',
  settings: {
    language: 'en-US',
    notifications: { email: true, sms: false }
  }
};
await indexedDBCache.set('appConfig', complexObject);

// Unset a nested property
await indexedDBCache.unset('appConfig.settings.notifications.sms');
const updatedAppConfig = await indexedDBCache.get('appConfig');
console.log(updatedAppConfig?.value);
// Output: { theme: 'dark', settings: { language: 'en-US', notifications: { email: true } } }

// Unset an array element (sets to null)
indexedDBCache.unsetSync('appConfig.items[1]');
const updatedItems = indexedDBCache.getSync('appConfig.items');
console.log(updatedItems?.value); // Output: ['apple', null, 'orange']

// Unset the entire 'appConfig' key
await indexedDBCache.unset('appConfig');
const appConfigAfterUnset = await indexedDBCache.get('appConfig');
console.log(appConfigAfterUnset); // Output: undefined

// Retrieving All Data
await indexedDBCache.set('product1', { id: 1, name: 'Laptop' });
await indexedDBCache.set('product2', { id: 2, name: 'Mouse' });

const allItemsMap = await indexedDBCache.getAll();
console.log(allItemsMap);
/* Output:
Map(2) {
  'product1' => { value: { id: 1, name: 'Laptop' }, expiresAt: ..., isExpired: false },
  'product2' => { value: { id: 2, name: 'Mouse' }, expiresAt: ..., isExpired: false }
}
*/

const allItemsJson = indexedDBCache.getJsonSync();
console.log(allItemsJson);
/* Output:
{  product1: { id: 1, name: 'Laptop' },
   product2: { id: 2, name: 'Mouse' }
} */

// Resetting the Cache
await indexedDBCache.resetWith({
  user: { id: 'user123', status: 'active' },
  app: { version: '1.0.0' }
}, { minutes: 5 }); // New TTL for reset

const resetData = await indexedDBCache.getJson();
console.log(resetData);
/* Output:
{
  user: { id: 'user123', status: 'active' },
  app: { version: '1.0.0' }
} */

// Getting Cache Info
const cacheInfo = indexedDBCache.info;
console.log(cacheInfo);
/* Output:
{
  dataBase: 'myAppCache',
  size: 'XXb', // e.g., '120b'
  options: {
    ttl: 300000, // 5 minutes in ms
    removeExpired: true,
    storage: 2 // StorageEngine.IndexedDB
  }
} */

Constructors

Constructor

ts
new HybridWebCache(baseName?, options?): HybridWebCache;

Constructor for Hybrid WebCache.

To reset the cache, use [resetWith()|resetWithSync()].

Note: For StorageType.IndexedDB, remember to call .init() if you plan to use synchronous methods

Parameters

baseName?

string = "HybridWebCache"

The base name of the cache.

options?

Partial<Options>

Returns

HybridWebCache

Default

ts
//options
{
	ttl: { seconds: 0, minutes: 0, hours: 1, days: 0 },
	removeExpired: true,
	storage: StorageType.Auto
}

Auxiliary Methods

bytes

Get Signature

ts
get bytes(): number;

Retrieves the total number of bytes used by the cache in the storage.

Returns

number

The total bytes used by the cache.


info

Get Signature

ts
get info(): object;

Provides information about the current cache.

Returns

object

An object containing:

  • dataBase: The name of the database used by the cache.
  • size: The calculated storage size in bytes represented as a string.
  • options: The current cache options including TTL converted to milliseconds.
ts
{
	dataBase: 'myAppCache',
	size: 'XXb', // e.g., '120b'
	options: {
		ttl: 300000, // 5 minutes in ms
		removeExpired: true,
		storage: 2 // StorageEngine.IndexedDB
	}
}
dataBase
ts
dataBase: string;
options
ts
options: Options;
size
ts
size: string;

length

Get Signature

ts
get length(): number;

Retrieves the number of items currently stored in the cache.

Returns

number

The count of items in the storage. *


storageType

Get Signature

ts
get storageType(): StorageEngine;

Returns the type of storage engine used by the cache.

Returns

StorageEngine

The type of storage engine used by the cache.

Get Methods

get()

ts
get<T>(keyPath, removeExpired): Promise<DataGetModel<T>>;

Retrieves the value associated with the specified keyPath from the storage engine.

If the value is found, it returns an object containing the value, expiration time, and expiration status. If the value is expired and the removeExpired flag is set to true, the expired value is removed from storage and undefined is returned.

Type Parameters

T

T extends ValueType

The type of the value being retrieved.

Parameters

keyPath

KeyPath

removeExpired

boolean = ...

A flag indicating whether to remove the key if its value is expired. Defaults to the instance's configured setting.

Returns

Promise<DataGetModel<T>>

A promise that resolves to an object containing the value and its metadata, or undefined if the value does not exist or is expired and removed.

Examples

Get the value at color.name.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}
const cache = new HybridWebCache();
const value = await cache.get('color.name');
// => "cerulean"

Get the value at color.code.hex.

ts
const hex = await cache.get('color.color.hex');
// => "#003BE6"

Get the value at color.hue.

ts
const value = await cache.get(['color', 'hue']);
// => undefined

Get the value at color.code.rgb[1].

ts
const value = await cache.get('color.code.rgb[1]');
// => 179

getAll()

ts
getAll<T>(removeExpired): Promise<Map<string, DataGetModel<T>>>;

Retrieves all key-value pairs from the storage engine.

If the removeExpired flag is set to true, expired values are removed from storage before being returned.

Type Parameters

T

T extends ValueType

Parameters

removeExpired

boolean = ...

A flag indicating whether to remove expired values from storage. Defaults to the instance's configured setting.

Returns

Promise<Map<string, DataGetModel<T>>>

A map of key-value pairs, where each value is an object containing the value, expiration time, and expiration status. If no values are found or if all values are expired and removed, null is returned.


getAllSync()

ts
getAllSync<T>(removeExpired): Map<string, DataGetModel<T>>;

Synchronously retrieves all items from storage as a map of key-value pairs, where each value is an object containing the value, expiration time, and expiration status.

If the removeExpired flag is set to true, expired values are removed from storage before being returned.

Type Parameters

T

T extends ValueType

Parameters

removeExpired

boolean = ...

A flag indicating whether to remove expired values from storage. Defaults to the instance's configured setting.

Returns

Map<string, DataGetModel<T>>

A map of key-value pairs, where each value is an object containing the value, expiration time, and expiration status. If no values are found or if all values are expired and removed, null is returned.


getJson()

ts
getJson(removeExpired): Promise<Record<string, ValueType>>;

Asynchronously retrieves all key-value pairs from the storage as a JSON object.

If the removeExpired flag is set to true, expired values are removed from storage before being included in the result.

Parameters

removeExpired

boolean = ...

A flag indicating whether to remove expired values from storage. Defaults to the instance's configured setting.

Returns

Promise<Record<string, ValueType>>

A promise that resolves to a JSON object containing all key-value pairs. If no items are found or all items are expired and removed, null is returned.


getJsonSync()

ts
getJsonSync(removeExpired): Record<string, ValueType>;

Synchronously retrieves all key-value pairs from the storage as a JSON object.

If the removeExpired flag is set to true, expired values are removed from storage before being included in the result.

Parameters

removeExpired

boolean = ...

A flag indicating whether to remove expired values from storage. Defaults to the instance's configured setting.

Returns

Record<string, ValueType>

A JSON object containing all key-value pairs. If no items are found or all items are expired and removed, null is returned.


getSync()

ts
getSync<T>(keyPath, removeExpired): DataGetModel<T>;

Synchronous version of get.

Retrieves the value associated with the specified keyPath from the storage engine.

If the value is found, it returns an object containing the value, expiration time, and expiration status. If the value is expired and the removeExpired flag is set to true, the expired value is removed from storage and undefined is returned.

Type Parameters

T

T extends ValueType

The type of the value being retrieved.

Parameters

keyPath

KeyPath

removeExpired

boolean = ...

A flag indicating whether to remove the key if its value is expired. Defaults to the instance's configured setting.

Returns

DataGetModel<T>

An object containing the value and its metadata, or undefined if the value does not exist or is expired and removed.

Examples

Get the value at color.name.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}

const value = cache.getSync('color.name');
// => "cerulean"

Get the value at color.code.hex.

ts
const hex = cache.getSync('color.color.hex');
// => "#003BE6"

Get the value at color.hue.

ts
const value = cache.getSync(['color', 'hue']);
// => undefined

Get the value at color.code.rgb[1].

ts
const value = cache.getSync('color.code.rgb[1]');
// => 179

Has Methods

has()

ts
has(keyPath): Promise<boolean>;

Checks if the given key path exists.

For sync method, use [hasSync()].

Parameters

keyPath

KeyPath

Returns

Promise<boolean>

A promise which resolves to true if the keyPath exists, else false.

Examples

Check if the value at color.name exists.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}

const exists = await cache.has('color.name');
// => true

Check if the value at color.hue exists.

ts
const exists = await cache.has(['color', 'hue']);
// => false

Check if the value at color.code.rgb[1] exists.

ts
const exists = await cache.has(color.code.rgb[1]);
// => true

hasSync()

ts
hasSync(keyPath): boolean;

Checks if the given key path exists.

For async method, use [has()].

Parameters

keyPath

KeyPath

Returns

boolean

true if the keyPath exists, else false.

Examples

Check if the value at color.name exists.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}

const exists = cache.hasSync('color.name');
// => true

Check if the value at color.hue exists.

ts
const exists = cache.hasSync(['color', 'hue']);
// => false

Check if the value at color.code.rgb[1] exists.

ts
const exists = cache.hasSync(color.code.rgb[1]);
// => true

Init Method

init()

ts
init(): Promise<void>;

Initializes the memory cache

This method is only necessary to use the synchronous functions of the IndexedDB strategy.

Returns

Promise<void>

A promise that resolves when the local storage is initialized.

Example

ts
const cache = new HybridWebCache("CacheDB", {storage: StorageEngine.IndexedDB});
await cache.init();

Reset Data Methods

resetWith()

ts
resetWith<T>(keyValues, ttl): Promise<void>;

Resets the storage with the provided key-value pairs and optional TTL.

This method first clears all existing entries in the storage engine. It then iterates over the provided key-value pairs, setting each one in the storage with the specified TTL. If no TTL is provided, the default TTL from the options is used.

Type Parameters

T

T extends ValueType

The type of values being stored.

Parameters

keyValues

RecordType<T>

ttl

Partial<TTL> = ...

Returns

Promise<void>

A promise that resolves when all key-value pairs have been set in the storage.


resetWithSync()

ts
resetWithSync<T>(keyValues, ttl): void;

Resets the storage with the provided key-value pairs and optional TTL.

This method first clears all existing entries in the storage engine. It then iterates over the provided key-value pairs, setting each one in the storage with the specified TTL. If no TTL is provided, the default TTL from the options is used.

Type Parameters

T

T extends ValueType

The type of values being stored.

Parameters

keyValues

RecordType<T>

ttl

Partial<TTL> = ...

Returns

void

Set Methods

set()

ts
set<T>(
   keyPath, 
   value, 
ttl): Promise<void>;

Sets the value for a given keyPath in the storage engine.

If the keyPath already exists, its value is updated with the provided value. If the keyPath does not exist, a new entry is created with the provided TTL.

Type Parameters

T

T extends ValueType

Parameters

keyPath

KeyPath

value

T

ttl

Partial<TTL> = ...

Returns

Promise<void>

Examples

Change the value at color.name to sapphire.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}

const cache = new HybridWebCache();
await cache.set('color.name', 'sapphire');

Set the value of color.hue to bluish.

ts
const cache = new HybridWebCache();
await cache.set(['color', 'hue'], 'bluish);

Change the value of color.code.

ts
const cache = new HybridWebCache();
await cache.set('color.code', { rgb: [16, 31, 134], hex: '#101F86' });

setSync()

ts
setSync<T>(
   keyPath, 
   value, 
   ttl): void;

Synchronous version of set.

Type Parameters

T

T extends ValueType

Parameters

keyPath

KeyPath

value

T

ttl

Partial<TTL> = ...

Returns

void

Examples

Change the value at color.name to sapphire.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}
cache.setSync('color.name', 'sapphire');

Set the value of color.hue to bluish.

ts
cache.setSync(['color', 'hue'], 'bluish);

Change the value of color.code.

ts
cache.setSync('color.code', { rgb: [16, 31, 134], hex: '#101F86' });

Unset Methods

unset()

Call Signature

ts
unset(): Promise<boolean>;

Unsets all key values.

For sync method, use [unsetSync()].

Returns

Promise<boolean>

A promise which resolves when the key values have been unset.

Example

Unsets all key values.

ts
await cache.unset();
await cache.getAll();
// => undefined

Call Signature

ts
unset(keyPath): Promise<boolean>;

Unsets the property at the given key path.

For sync method, use [unsetSync()].

Parameters
keyPath

KeyPath

Returns

Promise<boolean>

A promise which resolves when the setting has been unset.

Examples

Unset the property color.name.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}

await cache.unset('color.name');
await cache.get('color.name');
// => undefined

Unset the property color.code.rgba[1].

ts
await cache.unset('color.code.rgba[1]');
await cache.get('color.code.rgb');
// => [0, null, 230]

unsetSync()

Call Signature

ts
unsetSync(): boolean;

Unsets all key values.

For async method, use [unset()].

Returns

boolean

Example

Unsets all key values.

ts
cache.unsetSync();

Call Signature

ts
unsetSync(keyPath): boolean;

Unsets the property at the given key path.

For async method, use [unset()].

Parameters
keyPath

KeyPath

Returns

boolean

Examples

Unset the property color.name.

ts
// Given:
{
	"color": {
		"name": "cerulean",
		"code": {
			"rgb": [0, 179, 230],
			"hex": "#003BE6"
		}
	}
}

cache.unsetSync('color.name');
cache.getSync('color.name');
// => undefined

Unset the property color.code.rgba[1].

ts
cache.unsetSync('color.code.rgba[1]');
cache.getSync('color.code.rgb');
// => [0, null, 230]