Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Valthera Class Documentation

This documentation provides a detailed overview of the Valthera class, designed for performing CRUD operations on Valthera collections. The class uses the dbActionC module for file-based operations and executorC for managing execution tasks.

Class: Valthera

Constructor: Valthera(folder, options={}, fileCpu?)

Creates a new instance of the Valthera class.

  • Parameters:
    • folder (string): The folder path where the database files are stored.
    • options (object): Optional configuration options.
      • cacheThreshold (number, default: 3): The threshold for caching entries.
      • cacheTTL (number, default: 300000): Time-to-live for cache entries in milliseconds (default: 5 minutes).
    • fileCpu (FileCpu, optional): Custom file processor implementation. If not provided, defaults to vFileCpu.

Method: c(collection)

Creates a new instance of the CollectionManager class for the specified collection.

  • Parameters:
    • collection (string): The name of the collection.
  • Returns:
    • CollectionManager: A new instance of CollectionManager.

Method: async getCollections()

Gets the names of all available collections in the database.

  • Returns:
    • Promise<string[]>: A promise that resolves with an array of collection names.

Method: async checkCollection(collection)

Checks and creates the specified collection if it doesn't exist.

  • Parameters:

    • collection (string): The name of the collection to check.
  • Returns:

    • Promise<boolean>: A promise that resolves to true if the collection was created or already exists.

Method: async issetCollection(collection)

Checks if a collection exists.

  • Parameters:
    • collection (string): The name of the collection.
  • Returns:
    • Promise<boolean>: A promise that resolves to true if the collection exists, otherwise false.

Method: async add(collection, data, id_gen=true)

Adds data to a specified collection.

  • Parameters:

    • collection (string): The name of the collection.
    • data (Object): The data to add.
    • id_gen (boolean, default: true): Whether to generate an ID for the entry.
  • Returns:

    • Promise<T>: A promise that resolves with the added data.

Method: async find<T = Data>(collection, search, context={}, options={}, findOpts={})

Finds data in a collection based on a query.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • context (Object): The context object (for functions).
    • options (Object): Search options.
      • max (number, default: -1): Maximum number of entries to return.
      • reverse (boolean, default: false): Whether to reverse the search results.
    • findOpts (Object): Options for updating the search result.
  • Returns:

    • Promise<Array<T>>: A promise that resolves with the matching data.

Method: async findOne<T = Data>(collection, search, context={}, findOpts={})

Finds one matching entry in a collection.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • context (Object): The context object (for functions).
    • findOpts (Object): Options for updating the search result.
  • Returns:

    • Promise<T|null>: A promise that resolves with the found entry, or null if no match is found.

Method: async findStream<T = Data>(collection, search, context={}, findOpts={}, limit=-1)

Finds data in a collection as a stream.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • context (Object): The context object (for functions).
    • findOpts (Object): Options for updating the search result.
    • limit (number, default: -1): Maximum number of entries to return.
  • Returns:

    • Promise<AsyncGenerator<T>>: A promise that resolves with an asynchronous generator for streaming results.

Method: async update(collection, search, updater, context={})

Updates data in a collection.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • updater (function|Object): Update arguments.
    • context (Object): The context object (for functions).
  • Returns:

    • Promise<boolean>: A promise that resolves when the data is updated.

Method: async updateOne(collection, search, updater, context={})

Updates one entry in a collection.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • updater (function|Object): Update arguments.
    • context (Object): The context object (for functions).
  • Returns:

    • Promise<boolean>: A promise that resolves when the data is updated.

Method: async updateOneOrAdd(collection, search, updater, add_arg={}, context={}, id_gen=true)

Updates one entry or adds a new one if it doesn't exist.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • updater (function|Object): Update arguments.
    • add_arg (Object): Data to add if no match is found.
    • context (Object): The context object (for functions).
    • id_gen (boolean, default: true): Whether to generate an ID for the new entry.
  • Returns:

    • Promise<boolean>: A promise that resolves to true if the entry was updated, otherwise false.

Method: async remove(collection, search, context={})

Removes data from a collection.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • context (Object): The context object (for functions).
  • Returns:

    • Promise<boolean>: A promise that resolves when the data is removed.

Method: async removeOne(collection, search, context={})

Removes one entry from a collection.

  • Parameters:

    • collection (string): The name of the collection.
    • search (function|Object): The search query.
    • context (Object): The context object (for functions).
  • Returns:

    • Promise<boolean>: A promise that resolves when the entry is removed.

Method: async removeCollection(collection)

Removes the specified collection from the Valthera file system.

  • Parameters:

    • collection (string): The name of the collection to remove.
  • Returns:

    • Promise<boolean>: A promise that resolves when the collection is removed.

Method: async transaction(collection, transaction)

Executes a transaction on the specified collection.

  • Parameters:

    • collection (string): The name of the collection.
    • transaction (Transaction[]): An array of transaction operations.
  • Returns:

    • Promise<boolean>: A promise that resolves when the transaction is executed.

Predefined Search Options Quick Reference

Operators

Logical Operators

$and

Checks if all conditions in an array are true.

{
  $and: [
    { $gt: { age: 20 } },
    { $exists: { name: true } }
  ]
}

$or

Checks if at least one condition in an array is true.

{
  $or: [
    { $lt: { age: 20 } },
    { $gt: { age: 60 } }
  ]
}

$not

Negates a condition.

{
  $not: { $type: { age: "string" } }
}

Comparison Operators

$gt

Greater than comparison.

{ $gt: { age: 18 } }

$lt

Less than comparison.

{ $lt: { score: 100 } }

$gte

Greater than or equal comparison.

{ $gte: { price: 9.99 } }

$lte

Less than or equal comparison.

{ $lte: { quantity: 50 } }

$in

Checks if value is in an array.

{ $in: { status: ["active", "pending"] } }

$nin

Checks if value is not in an array.

{ $nin: { category: ["archived", "deleted"] } }

$between

Checks if a number is between two values (inclusive).

{ $between: { age: [18, 65] } }

Type and Existence Operators

$exists

Checks if a field exists (or doesn't exist).

{ $exists: { email: true, deletedAt: false } }

$type

Checks the type of a field.

{ $type: { age: "number", name: "string" } }

Array Operators

$arrinc

Checks if an array includes at least one of the specified values.

{ $arrinc: { tags: ["developer", "designer"] } }

$arrincall

Checks if an array includes all of the specified values.

{ $arrincall: { permissions: ["read", "write"] } }

$size

Checks the length of an array or string.

{ $size: { tags: 3 } }

String Operators

$regex

Tests a string against a regular expression.

{ $regex: { email: /^[^@]+@[^@]+\.[^@]+$/ } }

$startsWith

Checks if a string starts with a specified value.

{ $startsWith: { name: "Dr." } }

$endsWith

Checks if a string ends with a specified value.

{ $endsWith: { email: "@example.com" } }

Other Operators

$subset

Allows for skipping advanced validation for specific fields, applying only basic validation. This is useful when validation data may conflict with predefined functions (starting with $), while user data might also contain similar keys. Use this operator as a compromise.

{ $subset: { $lt: "John Doe" } } // chcek if "$lt" is "John Doe"

Examples

Complex Validation

const criteria = {
  $and: [
    {
      $or: [
        { $gt: { age: 18 } },
        { $exists: { guardianConsent: true } }
      ]
    },
    {
      $type: { email: "string" },
      $regex: { email: /^[^@]+@[^@]+\.[^@]+$/ }
    },
    {
      $arrincall: { roles: ["user"] },
      $not: { $in: { status: ["banned", "suspended"] } }
    }
  ]
};

const user = {
  age: 16,
  guardianConsent: true,
  email: "john@example.com",
  roles: ["user", "premium"],
  status: "active"
};

const isValid = hasFieldsAdvanced(user, criteria); // true

Nested Conditions

const criteria = {
  $and: [
    {
      $exists: { address: true },
      $type: { address: "object" }
    },
    {
      $or: [
        { $exists: { "address.zipCode": true } },
        {
          $and: [
            { $exists: { "address.city": true } },
            { $exists: { "address.country": true } }
          ]
        }
      ]
    }
  ]
};

const user = {
  address: {
    city: "New York",
    country: "USA"
  }
};

const isValid = hasFieldsAdvanced(user, criteria); // true

Error Handling

The function will throw an error if:

  • The fields parameter is not an object
  • The fields parameter is null

Always wrap the function call in a try-catch block when using with untrusted input:

try {
  const isValid = hasFieldsAdvanced(obj, criteria);
  // Handle result
} catch (error) {
  // Handle error
  console.error('Validation error:', error.message);
}

Predefined Find Options Quick Reference (Post Data-Matching Processing)

Description

These options are applied as part of a post-processing step after matching objects are found in the database (find stage) but before the data is returned to the client.
This process is designed to:

  1. Reduce data transfer size by removing unnecessary fields or selecting only the required ones.
  2. Customize results by transforming objects to meet specific requirements.

This optimization improves both performance and result usability, ensuring the client receives precisely the needed data in a compact form.


Execution Stack

  1. transform
  2. exclude
  3. select

Operators

select

Selects only specific fields to include in the final object.

// Original Object
{
    name: "John Doe",
    email: "john@example.com",
    age: 30,
    status: "active"
}

// Find Options
{
    select: ["name", "email"]
}

// Result
{
    name: "John Doe",
    email: "john@example.com"
}

exclude

Excludes specific fields from the object, removing unwanted data.

// Original Object
{
    name: "John Doe",
    email: "john@example.com",
    age: 30,
    status: "active"
}

// Find Options
{
    exclude: ["name"]
}

// Result
{
    email: "john@example.com",
    age: 30,
    status: "active"
}

transform

Applies a custom updater function to modify the object.

// Original Object
{
    name: "John Doe",
    email: "john@example.com",
    age: 30,
    status: "active"
}

// Find Options
{
    transform: (doc) => {
        doc.name = doc.name.toUpperCase();
        return doc;
    }
}

// Result
{
    name: "JOHN DOE",
    email: "john@example.com",
    age: 30,
    status: "active"
}

Combined Example

Using all operators together to demonstrate the execution stack.

// Original Object
{
    name: "John Doe",
    email: "john@example.com",
    age: 30,
    status: "active"
}

// Find Options
{
    transform: (doc) => {
        doc.newField = "added";
        doc.status = "inactive";
        return doc;
    },
    exclude: ["email", "newField"],
    select: ["name", "status"]
}

// Execution Steps:
1. transform:
   {
       name: "John Doe",
       email: "john@example.com",
       age: 30,
       status: "inactive",
       newField: "added"
   }
2. exclude:
   {
       name: "John Doe",
       age: 30,
       status: "inactive"
   }
3. select:
   {
       name: "John Doe",
       status: "inactive"
   }

// Final Result:
{
    name: "John Doe",
    status: "inactive"
}

This structured flow ensures flexible and predictable results, making it a powerful tool for refining and manipulating data.

Predefined Update Options Quick Reference

Arrays

$push

Adds an element to the end of an array.

{
    $push: { tags: "designer" }
}

Input:

{
    tags: ["developer"]
}

Output:

{
    tags: ["developer", "designer"]
}

$pushset

Adds an element to the end of an array and removes duplicates.

{
    $pushset: { tags: "designer" }
}

Input:

{
    tags: ["developer", "designer", "developer"]
}

Output:

{
    tags: ["developer", "designer"]
}

$pull

Removes a specific element from an array.

{
    $pull: { tags: "developer" }
}

Input:

{
    tags: ["developer", "designer"]
}

Output:

{
    tags: ["designer"]
}

$pullall

Removes all occurrences of specified elements from an array.

{
    $pullall: { tags: ["developer", "designer"] }
}

Input:

{
    tags: ["developer", "designer", "manager"]
}

Output:

{
    tags: ["manager"]
}

Numbers

$inc

Increments a numeric value by a given amount.

{
    $inc: { counter: 1 }
}

Input:

{
    counter: 5
}

Output:

{
    counter: 6
}

$dec

Decrements a numeric value by a given amount.

{
    $dec: { counter: 1 }
}

Input:

{
    counter: 5
}

Output:

{
    counter: 4
}

Objects

$merge

Merges a nested object, adding or updating properties.

{
    $merge: { settings: { theme: "dark" } }
}

Input:

{
    settings: { theme: "light", language: "en" }
}

Output:

{
    settings: { theme: "dark", language: "en" }
}

Others

$unset

Removes a specified key from an object.

{
    $unset: { age: true }
}

Input:

{
    name: "John",
    age: 30
}

Output:

{
    name: "John"
}

$rename

Renames a key in an object.

{
    $rename: { firstName: "name" }
}

Input:

{
    firstName: "John",
    lastName: "Doe"
}

Output:

{
    name: "John",
    lastName: "Doe"
}

Remote Valthera and Graph Valthera Client Documentation

remote Object Structure

  • name (string): The name of the Valthera.
  • url (string): The URL of the remote Valthera.
  • auth (string): The authentication token for accessing the Valthera.

Class: ValtheraRemote(remote)

ValtheraRemote is an extended version of the Valthera class, designed to handle API requests. It provides the same functionalities as Valthera, but enables remote communication, allowing you to interact with Valthera through HTTP requests.

Example Usage

const remoteDB = new ValtheraRemote({
    name: 'myRemoteDB',
    url: 'https://example.com/db',
    auth: 'your-auth-token'
});

or

const remoteDB = new ValtheraRemote('https://dbName:token@example.com/db');

Class: GraphRemote(remote)

GraphRemote is an extension of the Graph class, specifically designed for working with graph Valthera's over HTTP. It supports querying and modifying graph data, providing methods tailored for graph operations such as adding nodes, edges, and executing graph queries.

These constructors provide flexibility in initializing remote connections for both standard and graph-based Valthera databases.

Graph Database Documentation

This documentation provides an overview of the Graph class, which represents a graph database built on top of a custom DataBase module. The Graph class allows for managing graph structures by adding, removing, and querying edges between nodes in the database.

Class: Graph

Constructor: Graph(databaseFolder)

Initializes the graph database.

  • Parameters:
    • databaseFolder (string): The folder where the database is stored.

Method: async add(collection, nodeA, nodeB)

Adds an edge between two nodes in the specified collection.

  • Parameters:
    • collection (string): The name of the collection.
    • nodeA (string): The first node.
    • nodeB (string): The second node.
  • Returns:
    • Promise<Object>: A promise that resolves with the added edge.

Method: async remove(collection, nodeA, nodeB)

Removes an edge between two nodes in the specified collection.

  • Parameters:
    • collection (string): The name of the collection.
    • nodeA (string): The first node.
    • nodeB (string): The second node.
  • Returns:
    • Promise<boolean>: A promise that resolves to true if the edge is removed, otherwise false.

Method: async find(collection, node)

Finds all edges with either node equal to the specified node.

  • Parameters:
    • collection (string): The name of the collection.
    • node (string): The node to search for.
  • Returns:
    • Promise<Object[]>: A promise that resolves with an array of edges.

Method: async findOne(collection, nodeA, nodeB)

Finds one edge with either nodeA or nodeB as nodes.

  • Parameters:
    • collection (string): The name of the collection.
    • nodeA (string): The first node.
    • nodeB (string): The second node.
  • Returns:
    • Promise<Object|null>: A promise that resolves with the found edge or null if no edge is found.

Method: async getAll(collection)

Gets all edges in the specified collection.

  • Parameters:
    • collection (string): The name of the collection.
  • Returns:
    • Promise<Object[]>: A promise that resolves with all edges in the collection.

Method: async getCollections()

Returns the names of all available collections in the database.

  • Returns:
    • Promise<string[]>: A promise that resolves with an array of collection names.

Method: async checkCollection(collection)

Checks and creates the specified collection if it doesn't exist.

  • Parameters:
    • collection (string): The name of the collection.

Method: async issetCollection(collection)

Checks if the specified collection exists.

  • Parameters:
    • collection (string): The name of the collection.
  • Returns:
    • Promise<boolean>: A promise that resolves to true if the collection exists, otherwise false.

Method: removeCollection(collection)

Removes the specified collection from the database file system.

  • Parameters:
    • collection (string): The name of the collection to remove.
  • Returns:
    • void

Relation Class Documentation

The Relation class provides a mechanism to handle relationships between collections in a database. It supports one-to-one, one-to-many, and many-to-many relationships.

Class: Relation

Constructor: Relation(dbs)

Creates a new instance of the Relation class.

  • Parameters:
    • dbs (RelationTypes.DBS): An object mapping database names to DataBase or DataBaseRemote instances.

Method: async findOne(path, search, relations, select?)

Finds a single entry in a collection and resolves its relations.

  • Parameters:

    • path (RelationTypes.Path): A tuple specifying the database and collection.
    • search (Search): The search criteria.
    • relations (RelationTypes.Relation): The relations to resolve.
    • select (RelationTypes.FieldPath[], optional): Fields to select in the result.
  • Returns:

    • Promise<Object | null>: The found entry with resolved relations, or null if no match is found.

Method: async find(path, search, relations, select?, findOpts?)

Finds multiple entries in a collection and resolves their relations.

  • Parameters:

    • path (RelationTypes.Path): A tuple specifying the database and collection.
    • search (Search): The search criteria.
    • relations (RelationTypes.Relation): The relations to resolve.
    • select (RelationTypes.FieldPath[], optional): Fields to select in the results.
    • findOpts (DbFindOpts, optional): Options for the find operation.
  • Returns:

    • Promise<Object[]>: An array of found entries with resolved relations.

Relation Types

The Relation class supports the following relation types:

  1. One-to-One ("1"): Resolves a single related entry.
  2. One-to-Many ("1n"): Resolves multiple related entries.
  3. Many-to-Many ("nm"): Resolves all entries in the related collection.

Example Usage

import Relation from "@wxn0brp/db";
import { autoCreate } from "@wxn0brp/db";

// Create database instances
const db1 = autoCreate("path/to/db1");
const db2 = autoCreate("path/to/db2");

// Define databases
const dbs = {
    db1,
    db2
};

// Define relations
const relations = {
    author: {
        path: ["db1", "users"],
        pk: "authorId",
        fk: "_id",
        type: "1",
        select: ["name", "email"]
    },
    comments: {
        path: ["db2", "comments"],
        pk: "_id",
        fk: "postId",
        type: "1n",
        select: ["content", "createdAt"]
    }
};

// Create a Relation instance
const relation = new Relation(dbs);

// Find a single post with relations
const post = await relation.findOne(
    ["db1", "posts"],
    { _id: "post123" },
    relations,
    [["title"], ["author.name"], ["comments.content"]]
);

console.log(post);

// Find multiple posts with relations
const posts = await relation.find(
    ["db1", "posts"],
    { category: "tech" },
    relations,
    [["title"], ["author.name"], ["comments.content"]],
    { max: 10 }
);

console.log(posts);

This example demonstrates how to use the Relation class to resolve relationships between collections in different databases.