Skip to content

TypeScript SDK - Hash Client

The DBX TypeScript SDK provides a hash client for working with Redis hash data structures. This client offers type-safe methods for all hash operations with full TypeScript support.

Installation

npm install @0dbx/redis

Basic Usage

REST Client

import { DbxRedisClient } from "@0dbx/redis";
const client = new DbxRedisClient("http://localhost:3000");
const hashClient = client.hash;

WebSocket Client

import { DbxWsClient } from "@0dbx/redis";
const client = new DbxWsClient("ws://localhost:3000/redis_ws");
await client.connect();
const hashClient = client.hash;

Hash Operations

HSET - Set Hash Field

await hashClient.hset("user:123", "name", "John Doe");

HMSET - Set Multiple Fields

await hashClient.hmset("user:123", { name: "John Doe", email: "john@example.com" });

HGET - Get Field

const name = await hashClient.hget("user:123", "name");

HMGET - Get Multiple Fields

const values = await hashClient.hmget("user:123", ["name", "email"]);

HGETALL - Get All Fields

const allFields = await hashClient.hgetall("user:123");

HDEL - Delete Fields

const deleted = await hashClient.hdel("user:123", ["email"]);

HEXISTS - Check Field Exists

const exists = await hashClient.hexists("user:123", "name");

HKEYS - Get Field Names

const keys = await hashClient.hkeys("user:123");

HVALS - Get Values

const values = await hashClient.hvals("user:123");

HLEN - Get Hash Length

const length = await hashClient.hlen("user:123");

HINCRBY - Increment Field

const newValue = await hashClient.hincrby("user:123", "visits", 1);

HINCRBYFLOAT - Increment Field by Float

const score = await hashClient.hincrbyfloat("user:123", "score", 0.5);

HSETNX - Set Field if Not Exists

const created = await hashClient.hsetnx("user:123", "created_at", "2024-01-15T10:30:00Z");

HSTRLEN - Get Field String Length

const length = await hashClient.hstrlen("user:123", "name");

HRANDFIELD - Get Random Field

const randomField = await hashClient.hrandfield("user:123", 1, true);

Error Handling

All methods throw DBXError on failure. See String Client for error handling examples.

Best Practices

  • Use descriptive field names
  • Use HMSET/HMGET for batch operations
  • Validate field values
  • Set TTL on hash keys for temporary data
  • Use hash partitioning for large datasets