Abstract Key-Value Database Class

3.1.1 · active · verified Wed Apr 22

abstract-level provides an abstract interface for building lexicographically sorted key-value databases, serving as the foundation for the entire LevelDB ecosystem in JavaScript/TypeScript. It defines the core API, including operations like `put`, `get`, `del`, `batch`, and iterators, along with support for encodings, sublevels, events, and hooks. The current stable version is `3.1.1`, with active development reflected in regular minor and patch releases, and major versions introducing significant breaking changes (e.g., v2 to v3). Its key differentiator is being a specification rather than an implementation, allowing concrete database modules like `level` or `classic-level` to adhere to a common, well-defined API. It ships with comprehensive TypeScript types and leverages modern JavaScript features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic database operations (put, get, batch, iterate) using a `level` implementation conforming to `abstract-level`, highlighting type safety with generics and modern async/await patterns.

import { Level } from 'level';
import type { AbstractLevel, AbstractBatchOperation } from 'abstract-level';

interface MyValue { x: number; name: string; }

async function runDbExample() {
  // In a real application, replace 'level' with your chosen LevelDB implementation.
  // The generic types specify key and value types.
  const db: AbstractLevel<string, MyValue> = new Level<string, MyValue>('./my-db-path', {
    valueEncoding: 'json' // This will automatically JSON.stringify/parse values
  });

  try {
    console.log('Opening database...');
    await db.open();

    await db.put('item1', { x: 1, name: 'First Item' });
    await db.put('item2', { x: 2, name: 'Second Item' });

    const value1 = await db.get('item1');
    console.log(`Value for item1: ${JSON.stringify(value1)}`);

    // Batch operations
    const batchOperations: AbstractBatchOperation<string, MyValue>[] = [
      { type: 'put', key: 'item3', value: { x: 3, name: 'Third Item' } },
      { type: 'del', key: 'item1' }
    ];
    await db.batch(batchOperations);

    const value3 = await db.get('item3');
    console.log(`Value for item3: ${JSON.stringify(value3)}`);

    const deletedValue = await db.get('item1');
    console.log(`Value for item1 after delete (should be undefined): ${deletedValue}`);

    console.log('Iterating through remaining items:');
    for await (const [key, value] of db.iterator()) {
      console.log(`Key: ${key}, Value: ${JSON.stringify(value)}`);
    }

  } catch (error) {
    console.error('Database operation failed:', error);
  } finally {
    console.log('Closing database...');
    await db.close();
  }
}

runDbExample();

view raw JSON →