API

Complete API reference for Storage module

This page provides a complete API reference for all classes, interfaces, and utilities in the @vercube/storage package.

StorageManager (Class)

The StorageManager is the central service for managing storage instances. It handles mounting and provides a unified interface for storage operations across multiple storage backends.

Signature

class StorageManager {
  public mount<T extends Storage>(params: StorageTypes.Mount<T>): Promise<void>;
  public getStorage(name?: string): Storage | undefined;
  public getItem<T>(params: StorageTypes.GetItem): Promise<T | null>;
  public setItem<T, U>(params: StorageTypes.SetItem<T, U>): Promise<void>;
  public deleteItem(params: StorageTypes.DeleteItem): Promise<void>;
  public hasItem(params: StorageTypes.HasItem): Promise<boolean>;
  public getKeys(params: StorageTypes.GetKeys): Promise<string[]>;
  public clear(params: StorageTypes.Clear): Promise<void>;
  public size(params: StorageTypes.Size): Promise<number>;
}

Methods

mount()

Mounts a storage instance with the given configuration.

public async mount<T extends Storage>({ name, storage, initOptions }: StorageTypes.Mount<T>): Promise<void>

Parameters:

ParameterTypeRequiredDescription
namestringNoName for the storage instance (defaults to 'default')
storagetypeof StorageYesStorage class to instantiate
initOptionsobjectNoOptions passed to storage's initialize() method

Example:

import { StorageManager } from '@vercube/storage';
import { MemoryStorage } from '@vercube/storage/drivers/MemoryStorage';

const storageManager = container.get(StorageManager);

// Basic mount
storageManager.mount({
  name: 'cache',
  storage: MemoryStorage
});

// Mount with initOptions
storageManager.mount({
  name: 'redis',
  storage: RedisStorage,
  initOptions: {
    host: 'localhost',
    port: 6379
  }
});

getStorage()

Gets a mounted storage instance by name.

public getStorage(name: string = 'default'): Storage | undefined

Parameters:

ParameterTypeDescription
namestringName of the mounted storage (defaults to 'default')

Returns: Storage | undefined - The storage instance or undefined if not found

Example:

const cache = storageManager.getStorage('cache');
if (cache) {
  await cache.setItem('key', 'value');
}

getItem()

Retrieves an item from the specified storage.

public async getItem<T>({ storage, key }: StorageTypes.GetItem): Promise<T | null>

Parameters:

ParameterTypeRequiredDescription
storagestringNoName of the storage (defaults to 'default')
keystringYesKey of the item to retrieve

Returns: Promise<T | null> - The stored value or null if not found

Example:

const user = await storageManager.getItem<User>({
  storage: 'cache',
  key: 'user:123'
});

setItem()

Stores an item in the specified storage.

public async setItem<T, U>({ storage, key, value, options }: StorageTypes.SetItem<T, U>): Promise<void>

Parameters:

ParameterTypeRequiredDescription
storagestringNoName of the storage (defaults to 'default')
keystringYesKey under which to store the value
valueTYesValue to store
optionsUNoAdditional options (driver-specific)

Example:

await storageManager.setItem({
  storage: 'cache',
  key: 'user:123',
  value: { id: '123', name: 'John' }
});

deleteItem()

Deletes an item from the specified storage.

public async deleteItem({ storage, key }: StorageTypes.DeleteItem): Promise<void>

Parameters:

ParameterTypeRequiredDescription
storagestringNoName of the storage (defaults to 'default')
keystringYesKey of the item to delete

Example:

await storageManager.deleteItem({
  storage: 'cache',
  key: 'user:123'
});

hasItem()

Checks if an item exists in the specified storage.

public async hasItem({ storage, key }: StorageTypes.HasItem): Promise<boolean>

Parameters:

ParameterTypeRequiredDescription
storagestringNoName of the storage (defaults to 'default')
keystringYesKey to check for

Returns: Promise<boolean> - True if the item exists

Example:

const exists = await storageManager.hasItem({
  storage: 'cache',
  key: 'user:123'
});

getKeys()

Retrieves all keys from the specified storage.

public async getKeys({ storage }: StorageTypes.GetKeys): Promise<string[]>

Parameters:

ParameterTypeRequiredDescription
storagestringNoName of the storage (defaults to 'default')

Returns: Promise<string[]> - Array of all keys

Example:

const keys = await storageManager.getKeys({ storage: 'cache' });

// Filter keys by prefix manually
const userKeys = keys.filter(key => key.startsWith('user:'));

clear()

Clears all items from the specified storage.

public async clear({ storage }: StorageTypes.Clear): Promise<void>

Parameters:

ParameterTypeRequiredDescription
storagestringNoName of the storage (defaults to 'default')

Example:

await storageManager.clear({ storage: 'cache' });

size()

Gets the number of items in the specified storage.

public async size({ storage }: StorageTypes.Size): Promise<number>

Parameters:

ParameterTypeRequiredDescription
storagestringNoName of the storage (defaults to 'default')

Returns: Promise<number> - Number of items in storage

Example:

const count = await storageManager.size({ storage: 'cache' });
console.log(`Cache has ${count} items`);

Storage (Abstract Class)

Abstract base class for implementing storage providers. All storage implementations must extend this class.

Signature

abstract class Storage<T = undefined> {
  public abstract initialize(options: T): void | Promise<void>;
  public abstract getItem<T>(key: string): T | Promise<T>;
  public abstract setItem<T, U>(key: string, value: T, options?: U): void | Promise<void>;
  public abstract deleteItem(key: string): void | Promise<void>;
  public abstract hasItem(key: string): boolean | Promise<boolean>;
  public abstract getKeys(): string[] | Promise<string[]>;
  public abstract clear(): void | Promise<void>;
  public abstract size(): number | Promise<number>;
}

Methods

initialize()

Initializes the storage with configuration options. Called automatically when the storage is mounted.

public abstract initialize(options: T): void | Promise<void>

Parameters:

ParameterTypeDescription
optionsTProvider-specific configuration options

Example:

export class CustomStorage extends Storage<CustomOptions> {
  public async initialize(options: CustomOptions): Promise<void> {
    // Connect to database, initialize client, etc.
    this.client = await connectToService(options);
  }
}

getItem()

Retrieves a value by key.

public abstract getItem<T>(key: string): T | Promise<T>

Type Parameters:

ParameterDescription
TType of the stored value

Parameters:

ParameterTypeDescription
keystringThe key to retrieve

Returns: The value (implementation may return null if not found)

Example:

const user = await storage.getItem<User>('user:123');

setItem()

Stores a value with a key.

public abstract setItem<T, U>(key: string, value: T, options?: U): void | Promise<void>

Type Parameters:

ParameterDescription
TType of the value to store
UType of the optional options object

Parameters:

ParameterTypeDescription
keystringThe key to store under
valueTThe value to store
optionsUOptional driver-specific options

Example:

await storage.setItem('user:123', { id: '123', name: 'John' });

// With options (if supported by driver)
await storage.setItem('session:abc', data, { ttl: 3600 });

deleteItem()

Removes a value by key.

public abstract deleteItem(key: string): void | Promise<void>

Parameters:

ParameterTypeDescription
keystringThe key to remove

Example:

await storage.deleteItem('user:123');

hasItem()

Checks if a key exists in storage.

public abstract hasItem(key: string): boolean | Promise<boolean>

Parameters:

ParameterTypeDescription
keystringThe key to check

Returns: boolean - True if the key exists

Example:

const exists = await storage.hasItem('user:123');

getKeys()

Gets all keys in storage.

public abstract getKeys(): string[] | Promise<string[]>

Returns: Array of all keys

Example:

const allKeys = await storage.getKeys();

// Filter by prefix manually
const userKeys = allKeys.filter(key => key.startsWith('user:'));

clear()

Removes all items from storage.

public abstract clear(): void | Promise<void>

Example:

await storage.clear();

size()

Gets the number of items in storage.

public abstract size(): number | Promise<number>

Returns: Number of stored items

Example:

const count = await storage.size();
console.log(`Storage has ${count} items`);

Types

StorageTypes.Mount

Configuration for mounting a storage instance.

interface Mount<T extends Storage<unknown>> {
  name?: string;
  storage: IOC.Newable<T>;
  initOptions?: Parameters<T['initialize']>[0];
}

Properties:

PropertyTypeRequiredDescription
namestringNoName for the storage instance (defaults to 'default')
storageIOC.Newable<T>YesStorage class to instantiate
initOptionsobjectNoOptions passed to storage's initialize() method

StorageTypes.GetItem

Parameters for retrieving an item.

interface GetItem {
  storage?: string;
  key: string;
}

StorageTypes.SetItem

Parameters for storing an item.

interface SetItem<T, U = unknown> {
  storage?: string;
  key: string;
  value: T;
  options?: U;
}

StorageTypes.DeleteItem

Parameters for deleting an item.

interface DeleteItem {
  storage?: string;
  key: string;
}

StorageTypes.HasItem

Parameters for checking item existence.

interface HasItem {
  storage?: string;
  key: string;
}

StorageTypes.GetKeys

Parameters for retrieving keys.

interface GetKeys {
  storage?: string;
}

StorageTypes.Clear

Parameters for clearing storage.

interface Clear {
  storage?: string;
}

StorageTypes.Size

Parameters for getting storage size.

interface Size {
  storage?: string;
}

Type Declarations

Complete TypeScript type declarations for the storage module:

export abstract class Storage<T = undefined> {
  public abstract initialize(options: T): void | Promise<void>;
  public abstract getItem<T>(key: string): T | Promise<T>;
  public abstract setItem<T, U>(key: string, value: T, options?: U): void | Promise<void>;
  public abstract deleteItem(key: string): void | Promise<void>;
  public abstract hasItem(key: string): boolean | Promise<boolean>;
  public abstract getKeys(): string[] | Promise<string[]>;
  public abstract clear(): void | Promise<void>;
  public abstract size(): number | Promise<number>;
}

export class StorageManager {
  public mount<T extends Storage>(params: StorageTypes.Mount<T>): Promise<void>;
  public getStorage(name?: string): Storage | undefined;
  public getItem<T>(params: StorageTypes.GetItem): Promise<T | null>;
  public setItem<T, U>(params: StorageTypes.SetItem<T, U>): Promise<void>;
  public deleteItem(params: StorageTypes.DeleteItem): Promise<void>;
  public hasItem(params: StorageTypes.HasItem): Promise<boolean>;
  public getKeys(params: StorageTypes.GetKeys): Promise<string[]>;
  public clear(params: StorageTypes.Clear): Promise<void>;
  public size(params: StorageTypes.Size): Promise<number>;
}

export class MemoryStorage extends Storage {
  public initialize(): void;
  public getItem<T>(key: string): T;
  public setItem<T>(key: string, value: T): void;
  public deleteItem(key: string): void;
  public hasItem(key: string): boolean;
  public getKeys(): string[];
  public clear(): void;
  public size(): number;
}

export interface S3BaseOptions extends S3ClientConfig {
  bucket: string;
}

export class S3Storage extends Storage<S3BaseOptions> {
  public initialize(options: S3BaseOptions): Promise<void>;
  public getItem<T>(key: string): Promise<T>;
  public setItem<T, U>(key: string, value: T, options?: U): Promise<void>;
  public deleteItem(key: string): Promise<void>;
  public hasItem(key: string): Promise<boolean>;
  public getKeys(): Promise<string[]>;
  public clear(): Promise<void>;
  public size(): Promise<number>;
}

Troubleshooting

Storage Not Found

Problem: getStorage() returns undefined

Solution: Make sure you've mounted the storage before accessing it:

// Mount first
storageManager.mount({
  name: 'cache',
  storage: MemoryStorage
});

// Then access - check if storage exists
const cache = storageManager.getStorage('cache');
if (cache) {
  await cache.setItem('key', 'value');
}

// Or use StorageManager methods directly (recommended)
await storageManager.setItem({
  storage: 'cache',
  key: 'mykey',
  value: 'myvalue'
});

Type Mismatch

Problem: Retrieved data doesn't match expected type

Solution: Use proper type parameters and validate data:

// Specify expected type
const user = await storageManager.getItem<User>({
  storage: 'cache',
  key: 'user:123'
});

// Validate before using
if (user && isValidUser(user)) {
  // Safe to use
}

Memory Leaks with MemoryStorage

Problem: Application memory grows over time

Solutions:

  1. Clear old data periodically:
// Clear all data
await storageManager.clear({ storage: 'cache' });

// Or remove specific keys
const keys = await storageManager.getKeys({ storage: 'cache' });
const tempKeys = keys.filter(key => key.startsWith('temp:'));
for (const key of tempKeys) {
  await storageManager.deleteItem({ storage: 'cache', key });
}
  1. Implement TTL (time-to-live) for cached items:
interface CachedItem<T> {
  value: T;
  expiresAt: number;
}

async function getWithTTL<T>(key: string): Promise<T | null> {
  const cached = await storageManager.getItem<CachedItem<T>>({
    storage: 'cache',
    key
  });
  
  if (!cached) return null;
  
  if (Date.now() > cached.expiresAt) {
    await storageManager.deleteItem({ storage: 'cache', key });
    return null;
  }
  
  return cached.value;
}

async function setWithTTL<T>(key: string, value: T, ttlMs: number): Promise<void> {
  await storageManager.setItem({
    storage: 'cache',
    key,
    value: {
      value,
      expiresAt: Date.now() + ttlMs
    }
  });
}

Custom Storage Initialization Errors

Problem: "Failed to initialize storage"

Solutions:

  1. Check initialize() method doesn't throw:
public async initialize(options: any): Promise<void> {
  try {
    // initialization code
  } catch (error) {
    console.error('Storage init failed:', error);
    // Handle gracefully or re-throw
  }
}
  1. Verify storage is bound in container:
container.bind(CustomStorage);
  1. Check all required initOptions are provided:
storageManager.mount({
  name: 'custom',
  storage: CustomStorage,
  initOptions: {
    requiredOption: 'value' // Don't forget required options
  }
});
Previous

Overview

Real-time bidirectional communication with decorator-based API

Next