Introduction to Hyperbee
Hyperbee is a powerful distributed database built on the Hypercore Protocol. It provides an efficient and scalable way to store and retrieve structured data. Hyperbee is designed to work seamlessly with Hypercore, allowing for decentralized, peer-to-peer data sharing and synchronization.
Getting Started with Hyperbee
To get started with Hyperbee, you need to first install the required packages:
npm install @hypercore-protocol/hyperbee
Next, you can create a new Hyperbee instance:
const Hyperbee = require('@hypercore-protocol/hyperbee') const Hypercore = require('@hyperswarm/hypercore') const feed = new Hypercore('./my-hypercore-feed') const db = new Hyperbee(feed, { keyEncoding: 'utf-8', valueEncoding: 'json' })
Hyperbee API Examples
Creating and Opening a Database
Creating a new database:
const db = new Hyperbee(feed)
Opening an existing database:
const db = new Hyperbee(feed)
Inserting Data
To insert data into the database, use the put
method:
await db.put('key1', { name: 'Alice', age: 30 }) await db.put('key2', { name: 'Bob', age: 25 })
Retrieving Data
To retrieve data, use the get
method:
const value = await db.get('key1') console.log(value) // { name: 'Alice', age: 30 }
Deleting Data
To delete data, use the del
method:
await db.del('key2')
Listing Data
To list all entries in the database:
for await (const { key, value } of db.createReadStream()) { console.log(key, value) }
Batch Operations
Batch operations allow you to execute multiple operations atomically:
const batch = db.batch() await batch.put('key3', { name: 'Charlie', age: 22 }) await batch.del('key1') await batch.flush()
App Example Using Hyperbee APIs
Here is a simple example of a chat application using Hyperbee:
const Hyperbee = require('@hypercore-protocol/hyperbee') const Hypercore = require('@hyperswarm/hypercore') const feed = new Hypercore('./chat-feed') const db = new Hyperbee(feed, { keyEncoding: 'utf-8', valueEncoding: 'json' }) async function addMessage(username, message) { const timestamp = new Date().toISOString() const key = `${timestamp}:${username}` await db.put(key, { message }) console.log('Message added!') } async function getMessages() { for await (const { key, value } of db.createReadStream()) { const [timestamp, username] = key.split(':') console.log(`${timestamp} - ${username}: ${value.message}`) } } addMessage('alice', 'Hello there!') .then(() => getMessages())
In the example above, we create a new Hyperbee database and define functions to add and retrieve messages. You can run the addMessage
function to add new messages and the getMessages
function to list all messages in the chat.
Hyperbee is a versatile and efficient solution for building distributed applications. Whether you are working on a simple chat application or a large-scale data-driven project, Hyperbee provides the tools you need to manage and synchronize data effectively.
Hash: 130d64054eb8b7a076e576379c7823fd022b50cbceab5f668eb6df98016f06a3