vedadb-driver
v1.0.0
Published
Official VedaDB database driver - TCP and HTTP REST API clients for Node.js, Bun, Deno, and browsers
Maintainers
Readme
📊 VedaDB Driver
Official database driver for VedaDB — TCP and HTTP REST API clients
Features
- 🚀 Dual protocol support — TCP (Node.js native) and HTTP REST API (universal)
- 🌍 Universal — Works in Node.js (16+), Bun, Deno, and browsers
- 📘 TypeScript-first — Full type definitions with IntelliSense support
- ⚡ Zero dependencies — Lightweight with no runtime dependencies
- 🔌 Dual module support — Both ESM (
import) and CommonJS (require) - 🛡️ SQL injection protection — Safe tagged template literals and automatic escaping
- 💾 Built-in cache — In-memory caching API with TTL support
- 🔧 Fluent query builder — Chainable SQL builder API
Installation
npm install vedadb-driveryarn add vedadb-driverpnpm add vedadb-driverbun add vedadb-driverQuick Start
TCP Client (Node.js — Recommended)
The TCP client connects directly to VedaDB on port 6380 for maximum performance.
import { createClient } from "vedadb-driver";
const client = createClient({ host: "localhost", port: 6380 });
await client.connect();
// Select with filtering
const users = await client.select("users", {
where: { active: true },
orderBy: "created_at DESC",
limit: 10,
});
console.log(users.toObjects());
// → [{ id: 1, name: "Alice", active: true }, ...]
console.log(users.first());
// → { id: 1, name: "Alice", active: true }
console.log(users.pluck("name"));
// → ["Alice", "Bob", "Charlie"]
await client.disconnect();HTTP REST API Client (Browser / Universal)
The HTTP client uses fetch and works everywhere — browsers, Node.js 18+, Bun, and Deno.
import { createApiClient } from "vedadb-driver/api";
const api = createApiClient({ host: "localhost", port: 9090 });
// Test connection
const isUp = await api.testConnection();
console.log("Server up?", isUp);
// Query
const result = await api.query("SELECT * FROM users WHERE id = 1");
console.log(result.toObjects());
// Select helper
const posts = await api.select("posts", {
columns: ["id", "title"],
where: { published: true },
limit: 5,
});Using Standalone API Helpers
import {
vedaQuery,
vedaInsert,
vedaTestConnection,
} from "vedadb-driver/api";
// Quick query
const result = await vedaQuery("SELECT * FROM products");
// Quick insert
await vedaInsert("products", { name: "Widget", price: 19.99 });
// Test connection
const ok = await vedaTestConnection();Connection Configuration
Both clients accept a ConnectionConfig object:
interface ConnectionConfig {
host: string; // Default: "localhost"
port: number; // Default: 6380 (TCP) / 9090 (HTTP)
timeout?: number; // Default: 30000 (ms)
apiKey?: string; // Optional API key for authenticated endpoints
database?: string; // Optional default database name
}With API Key Authentication
const api = createApiClient({
host: "veda.example.com",
port: 9090,
apiKey: "your-secret-api-key",
});Singleton Pattern
import { getDefaultClient } from "vedadb-driver";
// Uses default config (localhost:6380)
const client = getDefaultClient();
await client.connect();
// All subsequent calls reuse the same connection
const result = await client.query("SELECT * FROM users");SQL Query Examples
Raw SQL Queries
// TCP
const result = await client.query("SELECT * FROM users WHERE age > 21");
console.log(result.toObjects());
// HTTP
const result = await api.query("SELECT * FROM users WHERE age > 21");Using the Fluent Query Builder
import { query, sql } from "vedadb-driver";
// Fluent builder
const sql1 = query()
.select("id", "name", "email")
.from("users")
.where({ active: true })
.orderBy("created_at DESC")
.limit(20)
.offset(40)
.build();
// → SELECT "id", "name", "email" FROM "users" WHERE "active" = TRUE
// ORDER BY created_at DESC LIMIT 20 OFFSET 40
// Tagged template (safe escaping)
const userId = 42;
const name = "O'Brien"; // quotes are escaped automatically
const sql2 = sql`SELECT * FROM users WHERE id = ${userId} AND name = ${name}`;
// → SELECT * FROM users WHERE id = 42 AND name = 'O''Brien'Insert
// TCP
await client.insert("users", {
name: "Alice",
email: "[email protected]",
age: 30,
});
// HTTP
await api.insert("users", {
name: "Alice",
email: "[email protected]",
});Update
// TCP
await client.update(
"users",
{ name: "Alice Smith", age: 31 }, // SET
{ id: 1 } // WHERE
);
// HTTP
await api.update("users", "status", "premium", { id: 1 });Delete
// TCP
await client.deleteFrom("users", { id: 1 });
// HTTP
await api.delete("users", { id: 1 });Transactions
TCP client supports transactions:
await client.transaction(async (trx) => {
await trx.insert("accounts", { user_id: 1, balance: 100 });
await trx.update("users", { has_account: true }, { id: 1 });
// Automatically commits on success, rolls back on error
});API Reference
TCP Client (vedadb-driver)
createClient(config?)
Creates a new TCP client instance.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| config.host | string | "localhost" | Server hostname |
| config.port | number | 6380 | TCP port |
| config.timeout | number | 30000 | Command timeout (ms) |
| config.apiKey | string | — | API key |
Returns a VedaClient with these methods:
| Method | Returns | Description |
|--------|---------|-------------|
| connect() | Promise<void> | Establish TCP connection |
| disconnect() | Promise<void> | Close connection |
| query(sql) | Promise<Result> | Execute a SELECT query |
| exec(sql) | Promise<Result> | Execute a statement |
| insert(table, data) | Promise<Result> | Insert a row |
| select(table, options?) | Promise<Result> | Select rows |
| update(table, set, where) | Promise<Result> | Update rows |
| deleteFrom(table, where) | Promise<Result> | Delete rows |
| transaction(fn) | Promise<T> | Run in transaction |
| cache | CacheAPI | In-memory cache |
| isConnected | boolean | Connection state |
Result Object
| Property | Type | Description |
|----------|------|-------------|
| columns | string[] | Column names |
| rows | unknown[][] | Row data |
| rowCount | number | Number of rows |
| message | string | Server message |
| toObjects() | T[] | Rows as objects |
| first() | T \| null | First row |
| pluck(col) | unknown[] | Extract column |
HTTP API Client (vedadb-driver/api)
createApiClient(config?)
Creates an HTTP API client using fetch.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| config.host | string | "localhost" | Server hostname |
| config.port | number | 9090 | HTTP port |
| config.fetch | fetch | globalThis.fetch | Custom fetch impl |
Returns a VedaApiClient:
| Method | Returns | Description |
|--------|---------|-------------|
| query(sql, db?) | Promise<Result> | Execute SQL |
| testConnection() | Promise<boolean> | Health check |
| insert(table, values) | Promise<{message}> | Insert row |
| update(table, col, val, where) | Promise<{message, affected}> | Update rows |
| delete(table, where) | Promise<{message, affected}> | Delete rows |
| exec(sql) | Promise<{message, rowCount}> | Execute SQL |
| select(table, opts?) | Promise<Result> | Select rows |
| listTables() | Promise<string[]> | List tables |
| schema(table) | Promise<object> | Table schema |
| getStatus() | VedaDBStatus | Connection info |
Cache API
Both clients expose an in-memory cache:
// Set with TTL (seconds)
client.cache.set("key", "value", 60);
// Get
const value = client.cache.get("key"); // "value" or null
// Delete
client.cache.del("key");
// Increment (atomic)
const count = client.cache.incr("counter"); // 1, 2, 3...SQL Builder (QueryBuilder)
import { QueryBuilder } from "vedadb-driver";
const qb = new QueryBuilder();
qb.select("id", "name").from("users").where({ active: true }).limit(10);
const sql = qb.build();
// Or reuse
qb.reset().select("*").from("posts").build();TypeScript Support
The package is written in TypeScript and ships with full type definitions.
import type { VedaClient, Result, SelectOptions, CacheAPI } from "vedadb-driver";
import type { VedaApiClient, VedaDBStatus } from "vedadb-driver/api";
interface User {
id: number;
name: string;
email: string;
}
// Typed results
const result: Result<User> = await client.select("users", { limit: 1 });
const users: User[] = result.toObjects();
const first: User | null = result.first();Using with Zustand / React
Here's a common pattern for integrating VedaDB with a Zustand store in a React application:
// store/useVedaStore.ts
import { create } from "zustand";
import { createApiClient, type VedaApiClient } from "vedadb-driver/api";
interface VedaState {
api: VedaApiClient;
isConnected: boolean;
isLoading: boolean;
error: string | null;
tables: string[];
connect: () => Promise<void>;
loadTables: () => Promise<void>;
}
export const useVedaStore = create<VedaState>((set, get) => ({
api: createApiClient({ host: "localhost", port: 9090 }),
isConnected: false,
isLoading: false,
error: null,
tables: [],
async connect() {
const { api } = get();
const ok = await api.testConnection();
set({ isConnected: ok, error: ok ? null : "Failed to connect" });
},
async loadTables() {
set({ isLoading: true, error: null });
try {
const { api } = get();
const tables = await api.listTables();
set({ tables, isLoading: false });
} catch (err: any) {
set({ error: err.message, isLoading: false });
}
},
}));// components/UserList.tsx
import { useVedaStore } from "../store/useVedaStore";
import { useEffect, useState } from "react";
export function UserList() {
const { api, isConnected } = useVedaStore();
const [users, setUsers] = useState<any[]>([]);
useEffect(() => {
if (!isConnected) return;
api.select("users", { where: { active: true } })
.then((r) => setUsers(r.toObjects()));
}, [api, isConnected]);
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
}Platforms
| Platform | TCP Client | HTTP Client | Notes |
|----------|-----------|-------------|-------|
| Node.js 18+ | ✅ | ✅ | Recommended |
| Node.js 16–17 | ✅ | ✅ | Requires fetch polyfill for HTTP |
| Bun | ✅ | ✅ | Native fetch support |
| Deno | ✅ | ✅ | Use npm:vedadb-driver |
| Browser | ❌ | ✅ | Native fetch support |
| Edge/Cloudflare | ❌ | ✅ | Native fetch support |
License
MIT © shubhammehta5407
Contributing
Contributions are welcome! Please open an issue or pull request on GitHub.
