Yjs LevelDB Persistence Adapter

0.2.0 · active · verified Tue Apr 21

y-leveldb is a persistence adapter for Yjs, the CRDT framework for real-time collaboration. It enables storing Yjs document updates persistently using LevelDB and its compatible implementations (like RocksDB, LMDB, or `level-mem`). The current stable version is `0.2.0`. Releases are infrequent but address compatibility, dependency updates, and bug fixes. Key differentiators include its flexibility to use various LevelUP-compatible storage backends, its direct integration into Yjs ecosystems (e.g., `y-websocket`), and its ability to manage multiple Yjs documents within a single database instance. The library provides a granular API for storing and retrieving document updates, state vectors, and custom metadata without necessarily hydrating a full Y.Doc object, which is crucial for efficient server-side synchronization and data management.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `y-leveldb`, store a Yjs document's state, and then retrieve it from the persistent storage, including setting and getting metadata. It shows basic CRUD operations for Yjs documents.

import * as Y from 'yjs'
import { LeveldbPersistence } from 'y-leveldb'

// Create a persistence instance pointing to a storage location.
// For in-memory, you could pass { level: require('level-mem') } as the second argument.
const persistence = new LeveldbPersistence('./yjs-storage')

async function runExample() {
  // Create a new Yjs document and make some changes.
  const ydoc = new Y.Doc()
  const yarray = ydoc.getArray('my-array')
  yarray.insert(0, ['item 1', 'item 2'])
  yarray.push(['item 3'])

  console.log('Initial Y.Doc content:', yarray.toArray())

  // Store the current state of 'my-doc' to LevelDB.
  await persistence.storeUpdate('my-doc', Y.encodeStateAsUpdate(ydoc))
  console.log('Document state stored.')

  // To retrieve data or sync, create a temporary Y.Doc from persistence.
  const persistedYDoc = await persistence.getYDoc('my-doc')
  const persistedYarray = persistedYDoc.getArray('my-array')
  console.log('Retrieved Y.Doc content:', persistedYarray.toArray())

  // Example of retrieving metadata
  await persistence.setMeta('my-doc', 'owner', 'Alice')
  const owner = await persistence.getMeta('my-doc', 'owner')
  console.log('Document owner:', owner)

  // Clean up example data (optional)
  // await persistence.clearDocument('my-doc')
  // console.log('Document cleared.')
}

runExample().catch(console.error)

view raw JSON →