Star ✨ on GitHub

Database

API reference for the Database class in Moonlink.js

Database Class

The Database class provides a robust key-value storage system for Moonlink.js, used internally to store player, node, and queue data. It utilizes a Write-Ahead Log (WAL) for data persistence and recovery.

Overview

Initialization

The Database is initialized asynchronously and should be accessed via the static create method.

class Database {
  static async create(manager: Manager): Promise<Database>;
}

Example
const manager = new Manager({ /* ... */ });
// Database is automatically created during manager.init()
await manager.init(client.user.id);
const database = manager.database;

Methods

Methods

Methods available in the Database class.

Available Methods

set

setmethod

Set Value

Stores a value associated with a key. If the key points to an object and the new value is also an object, they will be merged. Supports optional logging to WAL.

Parameters
keyrequiredstring
The key (path) to store the value (e.g., settings.volume, players.guildId.volume)
valuerequiredT
The value to store
logboolean
Optional: Whether to log this operation to the Write-Ahead Log. Defaults to true.

Returns & Example

Returnsvoid

database.set('settings.volume', 100);
database.set('queue.guildId', tracks, false); // Don't log to WAL

get

getmethod

Get Value

Retrieves a value by its key.

Parameters
keyrequiredstring
The key (path) to retrieve

Returns & Example

ReturnsT | undefined - The stored value or undefined if not found

const volume = database.get('settings.volume');
const queue = database.get('queue.guildId');

delete

deletemethod

Delete Value

Removes a value by its key. Supports optional logging to WAL.

Parameters
keyrequiredstring
The key (path) to delete
logboolean
Optional: Whether to log this operation to the Write-Ahead Log. Defaults to true.

Returns & Example

Returnsboolean - True if the key was deleted, false otherwise

const deleted = database.delete('settings.volume');
database.delete('queue.guildId', false); // Don't log to WAL

keys

keysmethod

Get All Keys

Retrieves all top-level and nested keys stored in the database.

Returns & Example

Returnsstring[] - An array of all keys.

const allKeys = database.keys();
console.log(allKeys);
// Example: ['players.guildId.volume', 'nodes.nodeId.sessionId']

clear

clearmethod

Clear All Data

Clears all data from the database, effectively resetting it. Also clears the Write-Ahead Log.

Returns & Example

Returnsvoid

database.clear();
console.log('Database cleared.');

shutdown

shutdownmethod

Shutdown Database

Gracefully shuts down the database, ensuring all pending writes are flushed and resources are released. This should be called before your application exits.

Returns & Example

ReturnsPromise<void>

await database.shutdown();
console.log('Database shut down.');

File Storage

Write-Ahead Log (WAL) Persistence

The Database class implements a Write-Ahead Log (WAL) system for robust data persistence and recovery.

Data changes are first written to a sequential log file (WAL) and then periodically compacted into a snapshot file. This ensures data integrity and allows for recovery in case of unexpected shutdowns.
  • Log Files: Changes are appended to data.{clientId}.wal.
  • Snapshot Files: Periodically, the in-memory state is saved to data.{clientId}.json.
  • Automatic Recovery: On initialization, the database replays the WAL to restore the latest state.
File Structure
moonlink.js/
  └── src/
      └── datastore/
          ├── data.123456789.json  // Snapshot of the database
          └── data.123456789.wal   // Write-Ahead Log

Usage Examples

Basic Usage

Examples of using the Database class.

// Access the database through the manager
const database = manager.database;

// Store player data
database.set(`players.${guildId}`, {
  volume: 100,
  paused: false,
  position: 0
});

// Retrieve player data
const playerData = database.get(`players.${guildId}`);

// Remove player data
database.delete(`players.${guildId}`);

// Get all keys
const allKeys = database.keys();

// Clear all data
database.clear();

// Shutdown the database (call before application exits)
await database.shutdown();