Complete API documentation for i45 v3.0.0+
The main class for managing browser storage operations with type safety.
new DataContext<T>(config?: DataContextConfig)Example:
import { DataContext, StorageLocations, Logger } from "i45";
const context = new DataContext<User>({
storageKey: "Users",
storageLocation: StorageLocations.LocalStorage,
loggingEnabled: true,
logger: new Logger(),
});new DataContext<T>(storageKey?: string, storageLocation?: StorageLocation)Example:
import { DataContext, StorageLocations } from "i45";
const context = new DataContext<User>("Users", StorageLocations.LocalStorage);The key used to store data in browser storage.
- Default:
"Items" - Mutable: Yes (can be changed after initialization)
const context = new DataContext();
console.log(context.storageKey); // "Items"
context.storageKey = "MyData";
console.log(context.storageKey); // "MyData"The storage type (localStorage or sessionStorage).
- Type:
StorageLocation(enum) - Default:
StorageLocations.LocalStorage - Mutable: Yes
import { StorageLocations } from "i45";
const context = new DataContext();
console.log(context.storageLocation); // StorageLocations.LocalStorage
context.storageLocation = StorageLocations.SessionStorage;Controls whether operations are logged.
- Default:
false - Mutable: Yes
const context = new DataContext({ loggingEnabled: true });
console.log(context.loggingEnabled); // true
context.loggingEnabled = false; // Disable loggingThe logger instance used for logging operations.
- Default:
null - Type:
Loggerfrom i45-jslogger or custom logger - Mutable: Yes (use
addClient()to set)
import { Logger } from "i45";
const context = new DataContext();
console.log(context.logger); // null
context.addClient(new Logger());
console.log(context.logger); // Logger instanceStores data using the current storageKey and storageLocation.
Parameters:
items: T[]- Array of items to store
Returns: Promise<DataContext<T>> - The context instance for chaining
Throws:
StorageKeyError- If storage key is invalidStorageLocationError- If storage location is invalidStorageQuotaError- If storage quota exceededDataServiceUnavailable- If storage service unavailable
Example:
const context = new DataContext<User>({ storageKey: "Users" });
await context.store([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
]);Stores data with a custom key, using the current storageLocation.
Parameters:
storageKey: string- Custom storage keyitems: T[]- Array of items to store
Returns: Promise<DataContext<T>>
Throws: Same as store()
Example:
const context = new DataContext<User>();
await context.storeAs("BackupUsers", [{ id: 1, name: "Alice" }]);async storeAt(storageKey: string, storageLocation: StorageLocation, items: T[]): Promise<DataContext<T>>
Stores data with full control over key and location.
Parameters:
storageKey: string- Custom storage keystorageLocation: StorageLocation- Storage typeitems: T[]- Array of items to store
Returns: Promise<DataContext<T>>
Throws: Same as store()
Example:
import { DataContext, StorageLocations } from "i45";
const context = new DataContext<User>();
await context.storeAt("TempUsers", StorageLocations.SessionStorage, [
{ id: 1, name: "Alice" },
]);Retrieves data using the current storageKey and storageLocation.
Returns: Promise<T[]> - Array of stored items
Throws:
StorageKeyError- If storage key is invalidStorageLocationError- If storage location is invalidDataRetrievalError- If retrieval failsDataServiceUnavailable- If storage service unavailable
Example:
const context = new DataContext<User>({ storageKey: "Users" });
const users = await context.retrieve();
console.log(users); // [{ id: 1, name: "Alice" }, ...]Retrieves data from a custom key, using the current storageLocation.
Parameters:
storageKey: string- Custom storage key
Returns: Promise<T[]>
Throws: Same as retrieve()
Example:
const context = new DataContext<User>();
const backupUsers = await context.retrieveFrom("BackupUsers");Retrieves data with full control over key and location.
Parameters:
storageKey: string- Custom storage keystorageLocation: StorageLocation- Storage type
Returns: Promise<T[]>
Throws: Same as retrieve()
Example:
import { DataContext, StorageLocations } from "i45";
const context = new DataContext<User>();
const tempUsers = await context.retrieveAt(
"TempUsers",
StorageLocations.SessionStorage
);Removes data using the current storageKey and storageLocation.
Returns: Promise<DataContext<T>> - The context instance for chaining
Throws:
StorageKeyError- If storage key is invalidStorageLocationError- If storage location is invalidDataServiceUnavailable- If storage service unavailable
Example:
const context = new DataContext<User>({ storageKey: "Users" });
await context.remove();Removes data from a custom key, using the current storageLocation.
Parameters:
storageKey: string- Custom storage key
Returns: Promise<DataContext<T>>
Throws: Same as remove()
Example:
const context = new DataContext<User>();
await context.removeFrom("BackupUsers");Removes data with full control over key and location.
Parameters:
storageKey: string- Custom storage keystorageLocation: StorageLocation- Storage type
Returns: Promise<DataContext<T>>
Throws: Same as remove()
Example:
import { DataContext, StorageLocations } from "i45";
const context = new DataContext<User>();
await context.removeAt("TempUsers", StorageLocations.SessionStorage);Clears all data from the current storageLocation (not just the current key).
Returns: Promise<DataContext<T>>
Throws:
DataServiceUnavailable- If storage service unavailable
Example:
const context = new DataContext();
await context.clear(); // Clears entire localStorageAdds a custom logger instance to the context.
Parameters:
logger: Logger- Logger instance from i45-jslogger or custom implementation
Returns: DataContext<T> - The context instance for chaining
Example:
import { DataContext, Logger } from "i45";
const context = new DataContext();
const logger = new Logger();
context.addClient(logger).loggingEnabled = true;Returns the current storage configuration.
Returns: Object with storageKey and storageLocation
Example:
const context = new DataContext({ storageKey: "MyData" });
const settings = context.getCurrentSettings();
console.log(settings);
// { storageKey: "MyData", storageLocation: StorageLocations.LocalStorage }Returns the currently loaded data (if any).
Returns: any[] - Array of data items
Example:
const context = new DataContext<User>();
await context.store([{ id: 1, name: "Alice" }]);
const data = context.getData();
console.log(data); // [{ id: 1, name: "Alice" }]Returns the log entries (if logging is enabled).
Returns: any[] - Array of log entries
Example:
const context = new DataContext({ loggingEnabled: true });
context.addClient(new Logger());
await context.store([{ id: 1, name: "Alice" }]);
const logs = context.printLog();
console.log(logs); // Array of log entriesConfiguration object for DataContext initialization (v3.0.0+).
interface DataContextConfig {
storageKey?: string;
storageLocation?: StorageLocation;
logger?: Logger | null;
loggingEnabled?: boolean;
}Properties:
-
storageKey?: string
The key used for storage operations.
Default:"Items" -
storageLocation?: StorageLocation
The storage type (localStorage or sessionStorage).
Default:StorageLocations.LocalStorage -
logger?: Logger | null
Logger instance for operation logging.
Default:null -
loggingEnabled?: boolean
Enable/disable logging.
Default:false
Example:
const config: DataContextConfig = {
storageKey: "UserPreferences",
storageLocation: StorageLocations.SessionStorage,
loggingEnabled: true,
logger: new Logger(),
};
const context = new DataContext<Preferences>(config);enum StorageLocations {
LocalStorage = "localStorage",
SessionStorage = "sessionStorage",
IndexedDB = "indexedDB", // NEW in v3.0.1
}Storage Capacities:
- LocalStorage: ~5-10MB (synchronous, key-value)
- SessionStorage: ~5-10MB (synchronous, session-only)
- IndexedDB: ~50MB+ (asynchronous, database with transactions)
Usage:
import { StorageLocations } from "i45";
// Use localStorage (default)
const localContext = new DataContext({
storageLocation: StorageLocations.LocalStorage,
});
// Use sessionStorage
const sessionContext = new DataContext({
storageLocation: StorageLocations.SessionStorage,
});
// Use IndexedDB for large datasets
const indexedContext = new DataContext({
storageLocation: StorageLocations.IndexedDB,
});Internal type representing a stored item.
interface StorageItem {
name: string;
value: string;
}Note: Users typically don't interact with this type directly. It's used internally for storage serialization.
i45 provides 6 custom error classes for specific error handling.
Thrown when a storage key is invalid (empty, whitespace-only, or too long).
Properties:
key: string- The invalid keymessage: string- Error description
Example:
import { StorageKeyError } from "i45";
try {
const context = new DataContext({ storageKey: "" });
await context.store([]);
} catch (error) {
if (error instanceof StorageKeyError) {
console.error("Invalid key:", error.key);
}
}Thrown when a storage location is invalid.
Properties:
location: string- The invalid locationvalidLocations: string[]- Valid location valuesmessage: string- Error description
Example:
import { StorageLocationError } from "i45";
try {
const context = new DataContext();
context.storageLocation = "invalidStorage" as any;
await context.store([]);
} catch (error) {
if (error instanceof StorageLocationError) {
console.error("Invalid location:", error.location);
console.error("Valid locations:", error.validLocations);
}
}Thrown when data retrieval fails (parse errors, missing data, etc.).
Properties:
key: string- The storage keycause?: Error- The underlying error (if any)message: string- Error description
Example:
import { DataRetrievalError } from "i45";
try {
const data = await context.retrieve();
} catch (error) {
if (error instanceof DataRetrievalError) {
console.error("Failed to retrieve from:", error.key);
if (error.cause) {
console.error("Underlying error:", error.cause);
}
}
}Thrown when storage quota is exceeded.
Properties:
key: string- The storage keystorageType: string- The storage type (localStorage/sessionStorage)message: string- Error description
Example:
import { StorageQuotaError } from "i45";
try {
await context.store(veryLargeArray);
} catch (error) {
if (error instanceof StorageQuotaError) {
console.error("Storage full:", error.storageType);
console.error("Failed key:", error.key);
// Handle quota error (e.g., clear old data, use different storage)
}
}Thrown when attempting to use persistence without enabling it.
Properties:
message: string- Error description
Example:
import { PersistenceServiceNotEnabled } from "i45";
try {
// Some operation requiring persistence
} catch (error) {
if (error instanceof PersistenceServiceNotEnabled) {
console.error("Persistence not enabled");
}
}Thrown when the storage service is unavailable (browser storage disabled, etc.).
Properties:
serviceName: string- The service name (e.g., "localStorage")message: string- Error description
Example:
import { DataServiceUnavailable } from "i45";
try {
await context.store([]);
} catch (error) {
if (error instanceof DataServiceUnavailable) {
console.error("Service unavailable:", error.serviceName);
// Handle unavailable service (e.g., fallback to memory storage)
}
}Centralized validation utilities (v3.0.0+).
Methods:
Validates a storage key.
Throws: StorageKeyError if invalid
Example:
import { ValidationUtils, StorageKeyError } from "i45";
try {
ValidationUtils.validateStorageKey("MyKey"); // OK
ValidationUtils.validateStorageKey(""); // Throws
} catch (error) {
if (error instanceof StorageKeyError) {
console.error("Invalid key");
}
}Validates a storage location.
Throws: StorageLocationError if invalid
Example:
import { ValidationUtils, StorageLocationError, StorageLocations } from "i45";
try {
ValidationUtils.validateStorageLocation(StorageLocations.LocalStorage); // OK
ValidationUtils.validateStorageLocation("invalid"); // Throws
} catch (error) {
if (error instanceof StorageLocationError) {
console.error("Invalid location");
}
}Validates an items array.
Throws: TypeError if items is not an array
Example:
import { ValidationUtils } from "i45";
try {
ValidationUtils.validateItems([1, 2, 3]); // OK
ValidationUtils.validateItems("invalid" as any); // Throws
} catch (error) {
console.error("Items must be an array");
}Validates a logger instance.
Throws: TypeError if logger doesn't have required methods
Example:
import { ValidationUtils, Logger } from "i45";
try {
ValidationUtils.validateLogger(new Logger()); // OK
ValidationUtils.validateLogger({}); // Throws
} catch (error) {
console.error("Invalid logger");
}Validates a configuration object.
Throws: Various errors if config is invalid
Example:
import { ValidationUtils } from "i45";
try {
ValidationUtils.validateConfig({
storageKey: "MyKey",
loggingEnabled: true,
}); // OK
} catch (error) {
console.error("Invalid config");
}Centralized error handling utilities (v3.0.0+).
Methods:
Handles and rethrows errors with context.
Parameters:
error: unknown- The error to handlecontext: string- Contextual information
Throws: The original error (or wrapped error)
Example:
import { ErrorHandler } from "i45";
try {
// Some operation
} catch (error) {
ErrorHandler.handle(error, "store operation");
}Service orchestration for storage operations (v3.0.0+).
Note: This class is used internally by DataContext. Users typically don't interact with it directly.
Usage (internal):
import { StorageManager, StorageLocations } from "i45";
const manager = new StorageManager();
await manager.store("MyKey", StorageLocations.LocalStorage, data);
const retrieved = await manager.retrieve(
"MyKey",
StorageLocations.LocalStorage
);
await manager.remove("MyKey", StorageLocations.LocalStorage);i45 includes i45-sample-data for quick testing and examples.
Pre-loaded JSON datasets.
Available Collections:
import { SampleData } from "i45";
// Access sample data
const states = SampleData.JsonData.States;
const books = SampleData.JsonData.Books;
const users = SampleData.JsonData.Users;
const products = SampleData.JsonData.Products;
const countries = SampleData.JsonData.Countries;
const terms = SampleData.JsonData.Terms;Example:
import { DataContext, SampleData } from "i45";
const context = new DataContext();
await context.store(SampleData.JsonData.Books);
const books = await context.retrieve();
console.log(books); // Array of book objectsSample data provides TypeScript types:
import { StateType, BookType, UserType } from "i45-sample-data";
const context = new DataContext<BookType>();
await context.store(SampleData.JsonData.Books);- README.md - Getting started guide
- migration.md - Migration from v2.x
- typescript.md - TypeScript usage guide
- examples.md - Comprehensive examples
- revisions.md - Version history