CacheClient API
Constructor
typescript
new CacheClient(config: ClientConfig)Parameters
| Param | Type | Default | Description |
|---|---|---|---|
| config.host | string | "127.0.0.1" | Server hostname |
| config.port | number | 3000 | Server port |
| config.retryAttempts | number | 3 | Retry on failure |
| config.retryDelay | number | 1000 | Delay between retries (ms) |
| config.timeout | number | 5000 | Request timeout (ms) |
Methods
connect(): Promise<void>
Connect to the cache server.
typescript
import { CacheClient } from "distributed-cache";
const client = new CacheClient({
host: "127.0.0.1",
port: 3000,
});
await client.connect();
console.log("Connected to cache server");disconnect(): Promise<void>
Disconnect from the server.
typescript
await client.disconnect();get(key: string): Promise<Value | null>
Retrieve a value from cache.
typescript
const user = await client.get("user:123");
if (user) {
console.log(user); // { name: "John", email: "john@example.com" }
} else {
console.log("Cache miss");
}set(key: string, value: Value, ttl?: number): Promise<void>
Store a value in cache.
typescript
// Store without TTL
await client.set("user:123", { name: "John" });
// Store with TTL (5 seconds)
await client.set("temp:data", "value", 5000);del(key: string): Promise<boolean>
Delete a key from cache.
typescript
const deleted = await client.del("user:123");
console.log(deleted); // true if existed, false otherwiseping(): Promise<boolean>
Check if server is alive.
typescript
const alive = await client.ping();
if (alive) {
console.log("Server is responding");
}isClientConnected(): boolean
Check if client is connected.
typescript
if (client.isClientConnected()) {
// safe to make requests
}Interfaces
ClientConfig
typescript
interface ClientConfig {
host: string; // default: "127.0.0.1"
port: number; // default: 3000
retryAttempts: number; // default: 3
retryDelay: number; // default: 1000
timeout: number; // default: 5000
}Example
typescript
import { CacheClient } from "distributed-cache";
const client = new CacheClient({
host: "127.0.0.1",
port: 3000,
retryAttempts: 3,
retryDelay: 1000,
timeout: 5000,
});
await client.connect();
// Store user session
await client.set("session:abc", { userId: 123, role: "admin" }, 3600000);
// Retrieve session
const session = await client.get("session:abc");
console.log(session); // { userId: 123, role: "admin" }
// Delete session on logout
await client.del("session:abc");
await client.disconnect();