alepha
Version:
Alepha is a convention-driven TypeScript framework for building robust, end-to-end type-safe applications, from serverless APIs to full-stack React apps.
288 lines (287 loc) • 10 kB
TypeScript
import * as _alepha_core0 from "alepha";
import { Descriptor, InstantiableClass, KIND } from "alepha";
import { DateTimeProvider, DurationLike, Timeout } from "alepha/datetime";
import * as _alepha_logger0 from "alepha/logger";
//#region src/providers/CacheProvider.d.ts
/**
* Cache provider interface.
*
* All methods are asynchronous and return promises.
* Values are stored as Uint8Array.
*/
declare abstract class CacheProvider {
/**
* Get the value of a key.
*
* @param name Cache name, used to group keys. Should be Redis-like "some:group:name" format.
* @param key The key of the value to get.
*
* @return The value of the key, or undefined if the key does not exist.
*/
abstract get(name: string, key: string): Promise<Uint8Array | undefined>;
/**
* Set the string value of a key.
*
* @param name Cache name, used to group keys. Should be Redis-like "some:group:name" format.
* @param key The key of the value to set.
* @param value The value to set.
* @param ttl The time-to-live of the key, in milliseconds.
*
* @return The value of the key.
*/
abstract set(name: string, key: string, value: Uint8Array, ttl?: number): Promise<Uint8Array>;
/**
* Remove the specified keys.
*
* @param name Cache name, used to group keys. Should be Redis-like "some:group:name" format.
* @param keys The keys to delete.
*/
abstract del(name: string, ...keys: string[]): Promise<void>;
abstract has(name: string, key: string): Promise<boolean>;
abstract keys(name: string, filter?: string): Promise<string[]>;
/**
* Remove all keys from all cache names.
*/
abstract clear(): Promise<void>;
}
//#endregion
//#region src/descriptors/$cache.d.ts
/**
* Creates a cache descriptor for high-performance data caching with automatic cache management.
*
* This descriptor provides a powerful caching layer that can significantly improve application performance
* by storing frequently accessed data in memory or external cache stores like Redis. It supports both
* function result caching and manual cache operations with intelligent serialization and TTL management.
*
* **Key Features**
*
* - **Function Result Caching**: Automatically cache function results based on input parameters
* - **Multiple Storage Backends**: Support for in-memory, Redis, and custom cache providers
* - **Intelligent Serialization**: Automatic handling of JSON, strings, and binary data
* - **TTL Management**: Configurable time-to-live with automatic expiration
* - **Cache Invalidation**: Pattern-based cache invalidation with wildcard support
* - **Environment Controls**: Enable/disable caching via environment variables
* - **Type Safety**: Full TypeScript support with generic type parameters
*
* ## Cache Strategies
*
* ### 1. Function Result Caching (Memoization)
* Automatically cache the results of expensive operations based on input parameters.
*
* ### 2. Manual Cache Operations
* Direct cache operations for custom caching logic and data storage.
*
* ## Storage Backends
*
* - **Memory**: Fast in-memory cache (default for development)
* - **Redis**: Distributed cache for production environments
* - **Custom Providers**: Implement your own cache storage backend
*
* @example
* **Basic function result caching:**
* ```ts
* import { $cache } from "alepha/cache";
*
* class DataService {
* // Cache expensive database queries
* getUserData = $cache({
* name: "user-data",
* ttl: [10, "minutes"],
* handler: async (userId: string) => {
* // Expensive database operation
* return await database.users.findById(userId);
* }
* });
*
* async getUser(id: string) {
* // This will hit cache on subsequent calls with same ID
* return await this.getUserData(id);
* }
* }
* ```
*
* @example
* **API response caching with custom key generation:**
* ```ts
* class ApiService {
* fetchUserPosts = $cache({
* name: "user-posts",
* ttl: [5, "minutes"],
* key: (userId: string, page: number) => `${userId}:page:${page}`,
* handler: async (userId: string, page: number = 1) => {
* const response = await fetch(`/api/users/${userId}/posts?page=${page}`);
* return await response.json();
* }
* });
* }
* ```
*
* @example
* **Manual cache operations for custom logic:**
* ```ts
* class SessionService {
* sessionCache = $cache<UserSession>({
* name: "user-sessions",
* ttl: [1, "hour"],
* provider: "memory" // Use memory cache for sessions
* });
*
* async storeSession(sessionId: string, session: UserSession) {
* await this.sessionCache.set(sessionId, session);
* }
*
* async getSession(sessionId: string): Promise<UserSession | undefined> {
* return await this.sessionCache.get(sessionId);
* }
*
* async invalidateUserSessions(userId: string) {
* // Invalidate all sessions for a user using wildcards
* await this.sessionCache.invalidate(`user:${userId}:*`);
* }
* }
* ```
*
* @example
* **Redis-backed caching for production:**
* ```ts
* class ProductService {
* productCache = $cache({
* name: "products",
* ttl: [1, "hour"],
* provider: RedisCacheProvider, // Use Redis for distributed caching
* handler: async (productId: string) => {
* return await this.database.products.findById(productId);
* }
* });
*
* async invalidateProduct(productId: string) {
* await this.productCache.invalidate(productId);
* }
*
* async invalidateAllProducts() {
* await this.productCache.invalidate("*");
* }
* }
* ```
*
* @example
* **Conditional caching with environment controls:**
* ```ts
* class ExpensiveService {
* computation = $cache({
* name: "heavy-computation",
* ttl: [1, "day"],
* disabled: process.env.NODE_ENV === "development", // Disable in dev
* handler: async (input: ComplexInput) => {
* // Very expensive computation that should be cached in production
* return await performHeavyComputation(input);
* }
* });
* }
* ```
*/
declare const $cache: {
<TReturn = string, TParameter extends any[] = any[]>(options?: CacheDescriptorOptions<TReturn, TParameter>): CacheDescriptorFn<TReturn, TParameter>;
[KIND]: typeof CacheDescriptor;
};
interface CacheDescriptorOptions<TReturn = any, TParameter extends any[] = any[]> {
/**
* The cache name. This is useful for invalidating multiple caches at once.
*
* Store key as `cache:$name:$key`.
*
* @default Name of the key of the class.
*/
name?: string;
/**
* Function which returns cached data.
*/
handler?: (...args: TParameter) => TReturn;
/**
* The key generator for the cache.
* If not provided, the arguments will be json.stringify().
*/
key?: (...args: TParameter) => string;
/**
* The store provider for the cache.
* If not provided, the default store provider will be used.
*/
provider?: InstantiableClass<CacheProvider> | "memory";
/**
* The time-to-live for the cache in seconds.
* Set 0 to skip expiration.
*
* @default 300 (5 minutes).
*/
ttl?: DurationLike;
/**
* If the cache is disabled.
*/
disabled?: boolean;
}
declare class CacheDescriptor<TReturn = any, TParameter extends any[] = any[]> extends Descriptor<CacheDescriptorOptions<TReturn, TParameter>> {
protected readonly env: {
CACHE_ENABLED: boolean;
CACHE_DEFAULT_TTL: number;
};
protected readonly dateTimeProvider: DateTimeProvider;
protected readonly provider: CacheProvider;
protected encoder: TextEncoder;
protected decoder: TextDecoder;
protected codes: {
BINARY: number;
JSON: number;
STRING: number;
};
get container(): string;
run(...args: TParameter): Promise<TReturn>;
key(...args: TParameter): string;
invalidate(...keys: string[]): Promise<void>;
set(key: string, value: TReturn, ttl?: DurationLike): Promise<void>;
get(key: string): Promise<TReturn | undefined>;
protected serialize<TReturn>(value: TReturn): Uint8Array;
protected deserialize<TReturn>(uint8Array: Uint8Array): Promise<TReturn>;
protected $provider(): CacheProvider;
}
interface CacheDescriptorFn<TReturn = any, TParameter extends any[] = any[]> extends CacheDescriptor<TReturn, TParameter> {
/**
* Run the cache descriptor with the provided arguments.
*/
(...args: TParameter): Promise<TReturn>;
}
//#endregion
//#region src/providers/MemoryCacheProvider.d.ts
type CacheName = string;
type CacheKey = string;
type CacheValue = {
data?: Uint8Array;
timeout?: Timeout;
};
declare class MemoryCacheProvider implements CacheProvider {
protected readonly dateTimeProvider: DateTimeProvider;
protected readonly log: _alepha_logger0.Logger;
protected store: Record<CacheName, Record<CacheKey, CacheValue>>;
get(name: string, key: string): Promise<Uint8Array | undefined>;
set(name: string, key: string, value: Uint8Array, ttl?: number): Promise<Uint8Array>;
del(name: string, ...keys: string[]): Promise<void>;
has(name: string, key: string): Promise<boolean>;
keys(name: string, filter?: string): Promise<string[]>;
clear(): Promise<void>;
}
//#endregion
//#region src/index.d.ts
/**
* Provides high-performance caching capabilities for Alepha applications with configurable TTL and multiple storage backends.
*
* The cache module enables declarative caching through the `$cache` descriptor, allowing you to cache method results,
* API responses, or computed values with automatic invalidation and type safety. It supports both in-memory and
* persistent storage backends for different performance and durability requirements.
*
* @see {@link $cache}
* @see {@link CacheProvider}
* @module alepha.cache
*/
declare const AlephaCache: _alepha_core0.Service<_alepha_core0.Module<{}>>;
//#endregion
export { $cache, AlephaCache, CacheDescriptor, CacheDescriptorFn, CacheDescriptorOptions, CacheProvider, MemoryCacheProvider };
//# sourceMappingURL=index.d.ts.map