Skip to content

CacheClient API

Constructor

typescript
new CacheClient(config: ClientConfig)

Parameters

ParamTypeDefaultDescription
config.hoststring"127.0.0.1"Server hostname
config.portnumber3000Server port
config.retryAttemptsnumber3Retry on failure
config.retryDelaynumber1000Delay between retries (ms)
config.timeoutnumber5000Request 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 otherwise

ping(): 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();

Released under the MIT License.