npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dbrevel/sdk

v0.2.3

Published

TypeScript SDK for DbRevel - AI-powered database SDK that converts natural language into secure, optimized queries for any database

Downloads

191

Readme

DbRevel TypeScript SDK

TypeScript client SDK for DbRevel - AI-powered database SDK that converts natural language into secure, optimized queries for any database.

Installation

npm install @dbrevel/sdk

Quick Start

import { DbRevelClient } from '@dbrevel/sdk';

const client = new DbRevelClient({
  baseUrl: 'http://localhost:8000',
  apiKey: 'your-project-api-key',
});

// Execute a natural language query
const result = await client.query("Get all users from Lagos");
console.log(result.data); // Array of results
console.log(result.metadata.execution_time_ms); // Execution time

Features

  • Natural language to database queries
  • Type-safe responses with TypeScript generics
  • Comprehensive error handling
  • Schema introspection
  • Health checks
  • Request cancellation support
  • Response validation
  • Request/response interceptors
  • Automatic retry with exponential backoff
  • Logging interceptors
  • Schema utilities and helper class

API Reference

DbRevelClient

Main client class for interacting with the DbRevel API.

Constructor

new DbRevelClient(config: DbRevelConfig)

Config:

  • baseUrl (string, required): API base URL
  • apiKey (string, required): Project API key (sent as X-Project-Key header)
  • timeout (number, optional): Request timeout in milliseconds (default: 30000)
  • retry (RetryConfig, optional): Retry configuration for automatic retries

Methods

query<T>(intent: string, options?: QueryOptions): Promise<QueryResult<T>>

Execute a natural language database query.

const result = await client.query<User>("Get all users");

Options:

  • dryRun (boolean): Validate query without executing
  • context (object): Additional context for query generation
  • signal (AbortSignal): Cancel request signal
getSchemas(): Promise<SchemasResponse>

Get schemas for all connected databases.

const schemas = await client.getSchemas();
console.log(schemas.databases.postgres.tables);
getSchema(databaseName: string): Promise<DatabaseSchema>

Get schema for a specific database.

const schema = await client.getSchema("postgres");
health(): Promise<HealthResponse>

Check API and database connectivity.

const health = await client.health();
console.log(health.status); // "healthy"

Error Handling

The SDK provides specific error types for better error handling:

import {
  DbRevelError,
  DbRevelTimeoutError,
  DbRevelAPIError,
  DbRevelValidationError,
  DbRevelNetworkError,
} from '@dbrevel/sdk';

try {
  await client.query("Get users");
} catch (error) {
  if (error instanceof DbRevelTimeoutError) {
    console.log('Request timed out');
  } else if (error instanceof DbRevelAPIError) {
    console.log(`API error: ${error.statusCode} - ${error.message}`);
  } else if (error instanceof DbRevelNetworkError) {
    console.log('Network error:', error.message);
  }
}

TypeScript Types

All types are exported for use in your code:

import type {
  QueryResult,
  QueryMetadata,
  QueryPlan,
  DatabaseSchema,
  SchemasResponse,
  HealthResponse,
} from '@dbrevel/sdk';

Examples

Basic Query

const result = await client.query("Get all users from Lagos");
console.log(result.data);

Dry Run (Validate Only)

const result = await client.query("Get users", { dryRun: true });
console.log(result.metadata.query_plan);

With Context

const result = await client.query("Get user orders", {
  context: { userId: 123 }
});

Request Cancellation

const controller = new AbortController();
setTimeout(() => controller.abort(), 5000); // Cancel after 5s

try {
  await client.query("Get users", { signal: controller.signal });
} catch (error) {
  if (error instanceof DbRevelTimeoutError) {
    console.log('Request cancelled');
  }
}

Schema Introspection

// Get all schemas
const schemas = await client.getSchemas();

// Get specific database schema
const postgresSchema = await client.getSchema("postgres");
console.log(postgresSchema.tables);

Health Check

const health = await client.health();
if (health.status === 'healthy') {
  console.log('All databases connected:', Object.keys(health.databases));
}

Schema Utilities

The SDK provides powerful utilities for working with database schemas:

import { SchemaHelper } from '@dbrevel/sdk';

// Get schemas and create helper
const schemas = await client.getSchemas();
const helper = new SchemaHelper(schemas);

// Get database names
const dbNames = helper.getDatabaseNames();

// Get table names from a database
const tableNames = helper.getTableNames('postgres');

// Get column names from a table
const columnNames = helper.getColumnNames('postgres', 'users');

// Get table schema
const usersTable = helper.getTable('postgres', 'users');

// Get primary key columns
const primaryKeys = helper.getPrimaryKeyColumns('postgres', 'users');

// Get foreign key relationships
const relationships = helper.getTableRelationships('postgres', 'users');

// Find tables containing a specific column
const tablesWithEmail = helper.findTablesByColumn('email');

// Check if table exists
if (helper.hasTable('postgres', 'users')) {
  console.log('Users table exists');
}

SchemaHelper Methods:

  • getDatabaseNames() - Get all database names
  • getDatabaseSchema(name) - Get schema for a database
  • getTableNames(database) - Get all table names
  • getCollectionNames(database) - Get all collection names
  • getTable(database, table) - Get table schema
  • getCollection(database, collection) - Get collection schema
  • getColumnNames(database, table) - Get column names
  • getColumn(database, table, column) - Get column schema
  • hasTable(database, table) - Check if table exists
  • hasCollection(database, collection) - Check if collection exists
  • getPrimaryKeyColumns(database, table) - Get primary key columns
  • getForeignKeyColumns(database, table) - Get foreign key columns
  • getTableRelationships(database, table) - Get table relationships
  • findTablesByColumn(columnName) - Find tables with column
  • findCollectionsByField(fieldName) - Find collections with field

Interceptors

Interceptors allow you to modify requests, responses, and handle errors:

import { createRequestLogger, createResponseLogger } from '@dbrevel/sdk';

// Add logging interceptors
client.useRequestInterceptor(createRequestLogger());
client.useResponseInterceptor(createResponseLogger());

// Custom request interceptor
client.useRequestInterceptor((config) => {
  // Add custom header
  return {
    ...config,
    headers: {
      ...config.headers,
      'X-Custom-Header': 'value',
    },
  };
});

// Custom error interceptor
client.useErrorInterceptor((error) => {
  console.error('Request failed:', error);
  // Optionally modify or rethrow error
  return error;
});

Retry Logic

Enable automatic retries with exponential backoff:

const client = new DbRevelClient({
  baseUrl: 'http://localhost:8000',
  apiKey: 'your-key',
  retry: {
    maxRetries: 3,
    retryDelay: 1000,        // Initial delay: 1s
    maxRetryDelay: 10000,     // Max delay: 10s
    backoffMultiplier: 2,     // Double delay each retry
    retryableStatusCodes: [500, 502, 503, 504],
    retryableErrorCodes: ['NETWORK_ERROR', 'TIMEOUT'],
  },
});

// Requests will automatically retry on network errors or 5xx status codes
const result = await client.query("Get users");

Retry Configuration:

  • maxRetries (number, default: 3): Maximum retry attempts
  • retryDelay (number, default: 1000): Initial delay in milliseconds
  • maxRetryDelay (number, default: 10000): Maximum delay between retries
  • backoffMultiplier (number, default: 2): Exponential backoff multiplier
  • retryableStatusCodes (number[], default: [500, 502, 503, 504]): HTTP status codes that trigger retry
  • retryableErrorCodes (string[], default: ['NETWORK_ERROR', 'TIMEOUT']): Error codes that trigger retry
  • shouldRetry (function, optional): Custom function to determine if request should be retried

Examples

See the examples/ directory for complete working examples:

  • Basic Query - Simple query execution
  • Dry Run - Validate queries without executing
  • Schema Introspection - Explore database schemas
  • Error Handling - Handle different error types
  • Interceptors - Use request/response interceptors
  • Retry Logic - Configure automatic retries
  • Typed Queries - Type-safe query results

Run an example:

npx ts-node examples/basic-query.ts

Development

# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test

# Watch mode
npm run dev

License

MIT