API
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:
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | No | Name for the storage instance (defaults to 'default') |
storage | typeof Storage | Yes | Storage class to instantiate |
initOptions | object | No | Options 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:
| Parameter | Type | Description |
|---|---|---|
name | string | Name 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
storage | string | No | Name of the storage (defaults to 'default') |
key | string | Yes | Key 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
storage | string | No | Name of the storage (defaults to 'default') |
key | string | Yes | Key under which to store the value |
value | T | Yes | Value to store |
options | U | No | Additional 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
storage | string | No | Name of the storage (defaults to 'default') |
key | string | Yes | Key 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
storage | string | No | Name of the storage (defaults to 'default') |
key | string | Yes | Key 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
storage | string | No | Name 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
storage | string | No | Name 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
storage | string | No | Name 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:
| Parameter | Type | Description |
|---|---|---|
options | T | Provider-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:
| Parameter | Description |
|---|---|
T | Type of the stored value |
Parameters:
| Parameter | Type | Description |
|---|---|---|
key | string | The 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:
| Parameter | Description |
|---|---|
T | Type of the value to store |
U | Type of the optional options object |
Parameters:
| Parameter | Type | Description |
|---|---|---|
key | string | The key to store under |
value | T | The value to store |
options | U | Optional 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:
| Parameter | Type | Description |
|---|---|---|
key | string | The 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:
| Parameter | Type | Description |
|---|---|---|
key | string | The 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:
| Property | Type | Required | Description |
|---|---|---|---|
name | string | No | Name for the storage instance (defaults to 'default') |
storage | IOC.Newable<T> | Yes | Storage class to instantiate |
initOptions | object | No | Options 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:
- 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 });
}
- 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:
- 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
}
}
- Verify storage is bound in container:
container.bind(CustomStorage);
- Check all required initOptions are provided:
storageManager.mount({
name: 'custom',
storage: CustomStorage,
initOptions: {
requiredOption: 'value' // Don't forget required options
}
});