@teliagen/cache
v0.4.3
Published
Teliagen official caching system with tagging and decorators
Downloads
32
Readme
@teliagen/cache
Caching system for the Teliagen Framework.
Overview
@teliagen/cache provides a flexible caching solution:
- In-Memory Cache – Fast default cache
- TTL Support – Time-to-live expiration
- Key Patterns – Wildcard key invalidation
- Driver Interface – Extensible for Redis, etc.
Installation
npm install @teliagen/cache
# or
pnpm add @teliagen/cacheQuick Start
import { Cache } from '@teliagen/cache';
const cache = new Cache();
// Set a value
await cache.set('user:123', { name: 'Alice', email: '[email protected]' });
// Get a value
const user = await cache.get('user:123');
// Set with TTL (60 seconds)
await cache.set('session:abc', { userId: '123' }, 60);
// Delete
await cache.delete('user:123');API Reference
Cache Class
class Cache {
constructor(options?: CacheOptions);
// Get value by key
get<T>(key: string): Promise<T | null>;
// Set value with optional TTL (seconds)
set<T>(key: string, value: T, ttl?: number): Promise<void>;
// Check if key exists
has(key: string): Promise<boolean>;
// Delete by key
delete(key: string): Promise<boolean>;
// Delete by pattern (e.g., 'user:*')
deletePattern(pattern: string): Promise<number>;
// Clear all cache
clear(): Promise<void>;
// Get or set (fetch if missing)
getOrSet<T>(key: string, factory: () => T | Promise<T>, ttl?: number): Promise<T>;
}Configuration
interface CacheOptions {
// Default TTL in seconds (0 = no expiration)
defaultTTL?: number;
// Maximum cache size (items)
maxSize?: number;
// Cache driver
driver?: CacheDriver;
}
const cache = new Cache({
defaultTTL: 3600, // 1 hour default
maxSize: 10000
});Usage Examples
Basic Caching
import { Cache } from '@teliagen/cache';
const cache = new Cache();
// Cache database query results
async function getUser(id: string) {
const cacheKey = `user:${id}`;
// Check cache first
let user = await cache.get(cacheKey);
if (!user) {
// Fetch from database
user = await User.findById(id);
// Cache for 5 minutes
await cache.set(cacheKey, user, 300);
}
return user;
}Get Or Set Pattern
// Simpler version using getOrSet
async function getUser(id: string) {
return cache.getOrSet(
`user:${id}`,
() => User.findById(id),
300 // 5 minutes TTL
);
}Cache Invalidation
// Delete specific key
await cache.delete('user:123');
// Delete all user cache
await cache.deletePattern('user:*');
// Delete all cache
await cache.clear();In Actions
import { Action, ActionProvider, Input } from '@teliagen/commons';
import { Cache } from '@teliagen/cache';
const cache = new Cache({ defaultTTL: 600 });
@ActionProvider('products', 'ProductActions')
class ProductActions {
@Action('getProduct')
async getProduct(@Input() input: { id: string }) {
return cache.getOrSet(
`product:${input.id}`,
() => Product.findById(input.id)
);
}
@Action('updateProduct')
async updateProduct(@Input() input: UpdateProductInput) {
const product = await Product.update(input.id, input);
// Invalidate cache
await cache.delete(`product:${input.id}`);
await cache.deletePattern(`products:list:*`);
return product;
}
}With Framework Feature
Use the Cache feature in your config:
// teliagen.config.ts
import { defineConfig, Cache } from '@teliagen/commons';
export default defineConfig({
features: [
Cache({
enabled: true,
ttl: 3600
})
]
});Then use @Cacheable decorator:
@ActionProvider('products', 'ProductActions')
class ProductActions {
@Action('listProducts')
@Cacheable({ ttl: 300, key: 'products:list:{page}' })
async listProducts(@Input() input: { page: number }) {
return Product.findAll({ offset: input.page * 20, limit: 20 });
}
}Custom Drivers
Redis Driver
import { Cache, CacheDriver } from '@teliagen/cache';
import Redis from 'ioredis';
class RedisDriver implements CacheDriver {
private client: Redis;
constructor(options: RedisOptions) {
this.client = new Redis(options);
}
async get<T>(key: string): Promise<T | null> {
const value = await this.client.get(key);
return value ? JSON.parse(value) : null;
}
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
const serialized = JSON.stringify(value);
if (ttl) {
await this.client.setex(key, ttl, serialized);
} else {
await this.client.set(key, serialized);
}
}
async delete(key: string): Promise<boolean> {
const result = await this.client.del(key);
return result > 0;
}
async deletePattern(pattern: string): Promise<number> {
const keys = await this.client.keys(pattern);
if (keys.length === 0) return 0;
return this.client.del(...keys);
}
async clear(): Promise<void> {
await this.client.flushdb();
}
}
// Use it
const cache = new Cache({
driver: new RedisDriver({ host: 'localhost', port: 6379 })
});Requirements
- Node.js >= 18.0.0
Documentation
For full documentation, visit docs.teliagen.org.
License
Apache-2.0
