Class: BeanBagDB

BeanBagDB(db_instance)

The core BeanBagDB class abstracts the database logic making it adaptable to both frontend and backend application. It is designed to be independent of any specific database allowing for integration with many databases.

Initialization : Upon initializing the BeanBagDB object, the user must pass a JSON object with essential parameters such as the encryption key. Access to the database is provided through the "api" object which should include asynchronous methods that handle basic CRUD operations and other utility functions.

This class can serve a foundation for building database specific BeanBagDb classes.

Method types The main methods allow users to interact with the database through the BeanBagDB class. All methods follow the snake_case naming convention (lowercase letters separated by underscores).

The types of methods include:

  • Setup methods: These methods are used for setting up the system, such as 'ready' and 'initialize'.
  • CRUD methods: These methods handle basic database operations like 'create', 'read', 'update', and 'delete'.
  • Search methods: Like 'search' to find multiple documents based on criteria. (Note: read fetches a single document, while search fetches multiple documents matching a criteria).
  • Plugin methods: These methods manage loading and using plugins (see plugins).
  • Utility methods: These methods don't directly interact with the database but serve specific purposes, such as returning the current UTC timestamp. These methods are prefixed with util_.

For more details, see the getting-started tutorial. The class also includes internal methods intended for use within the class. These methods are not intended for external access and are prefixed with an underscore (they are not visible in the documentation, but you can check the source code).

Constructor

new BeanBagDB(db_instance)

Initializes the BeanBagDB instance.

Parameters:
Name Type Description
db_instance object

Database configuration object.

Properties
Name Type Description
name string

The name of the local database.

encryption_key string

A key for encrypting documents (minimum 20 characters).

api object

The API object containing database-specific CRUD operations.

Properties
Name Type Description
insert function

Inserts a document into the database.

update function

Updates an existing document in the database.

delete function

Deletes a document from the database.

search function

Searches for documents based on a query (returns an array of JSON).

get function

Retrieves a document by its ID.

createIndex function

Creates an index in the database based on a filter.

utils object

Utility functions for encryption and other operations.

Properties
Name Type Description
encrypt function

Encrypts a document.

decrypt function

Decrypts a document.

ping function

Checks the database connection.

validate_schema function

Validates the database schema.

Classes

BeanBagDB

Members

error_codes

Static property containing predefined error codes for common errors. These error codes can be used throughout the class to handle specific exceptions.

Properties:
Name Type Description
error_codes Object

An object with key-value pairs representing error codes and their messages.

Properties
Name Type Description
key_short string

The encryption key must contain at least 20 characters.

not_active string

The database is not ready. Run the ready() method first.

schema_not_found string

No schema found for the specified name.

doc_not_found string

No document found for the provided search criteria.

Methods

(async) create(schema, data, metaopt, settingsopt) → {Promise.<{id: string}>}

Creates a document for the given schema into the database.

This method validates the input data and schema before inserting a new document into the database.

Parameters:
Name Type Attributes Default Description
schema string

The schema name for the document, e.g., "contact".

data object

The document data, e.g., { "name": "", "mobile": "", ... }.

meta object <optional>
{}

Optional metadata associated with the document.

settings object <optional>
{}

Optional settings that may affect document creation behavior.

Throws:
  • Throws an error if insertion checks fail or if there is an issue with the database operation.
Type
Error
Returns:
  • A promise that resolves with the newly inserted document's ID.
Type
Promise.<{id: string}>

(async) delete(doc_id)

Deletes a document from the database by its ID.

Parameters:
Name Type Description
doc_id String

The ID of the document to delete.

Throws:

(async) get(special_doc_type, criteriaopt) → {Object}

Retrieves special types of documents from the database, such as schema documents or blank documents for a given schema. It handles system-related data and throws errors for invalid document types or if the document is not found.

Parameters:
Name Type Attributes Default Description
special_doc_type String

The type of special document to fetch. Supported types include: - 'schema': Retrieves a schema document based on the criteria provided.

criteria Object <optional>
{}

Criteria used to search for the special document. For example, to search for a schema, the criteria should include the name.

Throws:
  • Throws if the special_doc_type is not recognized.

    Type
    ValidationError
  • Throws if the requested document is not found in the database.

    Type
    DocNotFoundError
Returns:

The fetched special document based on the type and criteria.

Type
Object

(async) initialize() → {Promise.<void>}

Initializes the database with the required schemas.

This method is responsible for:

  • Verifying the existence and latest version of the schema_schema document.
  • Upgrading or inserting a new system schema if the version is outdated or missing.
  • Logging initialization steps in the system logs.
  • Updating the database version if needed.

This method is usually called automatically by 'ready' if required but can be run manually if needed.

Throws:
  • Throws an error if schema initialization fails.
Type
Error
Returns:
  • Resolves when the initialization is complete.
Type
Promise.<void>

metadata() → {DBMetaData}

Retrieves metadata for the current database object.

To Do:
  • Include additional metadata: document count, schema count, records for each schema, size of the database.
Returns:

An object containing system metadata.

Type
DBMetaData

(async) read(criteria, include_schemaopt) → {Promise.<Object>}

Reads a document from the database based on the provided criteria.

There are three valid ways to search for one document:

  1. By _id (e.g., { "_id": "document_id" })
  2. By link (e.g., { "link": "some_link" })
  3. By schema's primary key (e.g., { "schema": "schema_name", "data": { "primary_key_1": "value", "primary_key_2": "value" }})

If the document does not exist, an error will be thrown.

Parameters:
Name Type Attributes Default Description
criteria Object

The search criteria for the document.

Properties
Name Type Attributes Description
_id string <optional>

The document ID for direct lookup.

link string <optional>

A unique link identifier for the document.

schema string <optional>

The schema name used when searching by primary keys.

data Object <optional>

Data object containing the schema's primary keys for search.

include_schema boolean <optional>
false

Whether to include the schema object in the returned result.

Throws:
Returns:
  • Returns an object with the document (doc) and optionally the schema (schema).
Type
Promise.<Object>

(async) ready() → {Promise.<void>}

Checks if the database is ready to be used. It is important to run this method after the class is initialized.

This method performs the following actions:

  • Pings the database.
  • Searches the database for the system_setting.beanbagdb_version document.
  • Sets the class state as active if the version matches the current BeanBagDB version.
  • If the version does not match, calls initialize() to set up the database to the latest version.
To Do:
  • Code to ping the DB and throw Connection error if failed to connect
Returns:
  • Resolves when the database has been verified and initialized.
Type
Promise.<void>

(async) save_setting_doc(name, new_data, schemaopt) → {Promise.<object>}

Updates a setting document if it already exists in the database or creates a new document Inserts or updates a setting in the system settings schema.

This method either:

  • Updates an existing document if the setting with the given name already exists in the database.
  • Inserts a new document if no matching setting is found.

If the setting exists and the value is an array, the behavior depends on the on_update_array key:

  • "append": Appends the new value to the existing array.
  • "update": Replaces the current array with the new value.
Parameters:
Name Type Attributes Default Description
name string

The name of the setting to insert or update.

new_data object

The new data to insert or update.

Properties
Name Type Attributes Description
value *

The value to insert or update.

on_update_array string <optional>

Optional behavior for handling arrays, either "append" or "update".

schema object <optional>
{}

Optional schema to validate the data against (currently not implemented).

Throws:
  • Throws an error if new_data or new_data.value is not provided, or if on_update_array is invalid.
Type
Error
Returns:
  • The updated or newly inserted document.
Type
Promise.<object>

Searches for documents in the database for the specified query. The query are Mango queries. One field is mandatory : Schema E.g

Parameters:
Name Type Description
criteria Object

(async) update(doc_search_criteria, rev_id, updates, update_sourceopt, save_conflictopt) → {Object}

Updates the data and metadata of a document.

Frequently Asked Questions:

  • Which data fields can be edited?

    • All fields except for the ones listed in the schema's settings.non_editable_fields can be edited. If this setting is blank, all fields are editable by default.
  • Are primary key fields editable?

    • Yes, but a validation check ensures that primary key policies are not violated before the update is applied.
Parameters:
Name Type Attributes Default Description
doc_search_criteria Object

The criteria used to search for the document (e.g., {"_id": "document_id"}, {"link": "some_link"}, {"schema": "schema_name", "data": {primary_key_fields}}).

rev_id String

The document's revision ID (_rev) used for version control and conflict detection.

updates Object

The updated values for the document, structured as {data: {}, meta: {}}. Only the fields to be updated need to be provided.

update_source String <optional>
"api"

Identifies the source of the update (default: "api").

save_conflict Boolean <optional>
true

If true, conflicting updates will be saved separately in case of revision mismatches.

Behavior:

  • Retrieves the document based on the provided search criteria.
  • Checks the revision ID to detect potential conflicts. (To be implemented: behavior when the rev_id does not match).
  • Validates editable fields against schema.settings.editable_fields (or allows editing of all fields if not specified).
  • Encrypts fields if encryption is required by the schema settings.
  • Updates the meta fields (such as updated_on and updated_by) and saves the updated document to the database.

Returns:

Throws:
    • If a document with conflicting primary keys already exists.
    Type
    DocUpdateError
    • If the provided data or metadata is invalid according to the schema.
    Type
    ValidationError
Returns:

The result of the document update operation.

Errors:

  • Throws an error if a document with the same primary keys already exists .
  • Throws a DocUpdateError if a primary key conflict is detected during the update.
Type
Object

(async) update_indexes()

Adds indexes for all the schemas in the data base. This is important to make search faster. This must be done every time a new schema is introduced in the database

util_check_required_fields(requiredFields, obj)

Validates that the required fields are present in the provided object.

Parameters:
Name Type Description
requiredFields Array.<string>

An array of field names that are required.

obj object

The object to check for the required fields.

Throws:

If any of the required fields are missing, an error is thrown.

Type
ValidationError

util_filter_object(obj, fields) → {Object}

Filters an object, returning a new object that only contains the specified fields.

Parameters:
Name Type Description
obj Object

The object to filter.

fields Array.<String>

An array of field names to retain in the filtered object.

Returns:
  • A new object containing only the fields that exist in obj from the fields array.

Example:

const data = { name: "Alice", age: 25, location: "NY" }; const result = util_filter_object(data, ["name", "age"]); // result: { name: "Alice", age: 25 }

Type
Object

Generates a random link composed of four words from a predefined dictionary.

The words are selected randomly, and the resulting link is formatted as a hyphen-separated string. This can be useful for creating link for documents.

Returns:

A hyphen-separated string containing three randomly selected words from the dictionary. For example: "banana-earth-rain".

Type
String

util_validate_data(schema_obj, data_obj)

Validates a data object against a provided JSON schema It relies on the external API provided by the user

Parameters:
Name Type Description
schema_obj Object

The JSON schema object to validate against

data_obj Object

The data object to validate

Throws:

If the data object does not conform to the schema

Type
Error

util_validate_schema_object(schema_doc)

Validates the structure and content of a schema object.

This method checks the following conditions:

  • The schema must have a 'type' field, which should be 'object'.
  • The 'properties' field must be an object and contain at least one property.
  • The 'additionalProperties' field must be present and of type boolean.
  • Primary keys must be defined in the schema and cannot be of type 'object' or 'array'.
  • Non-editable fields must be defined in the schema.
  • Encrypted fields must be defined in the schema, of type 'string', and cannot include primary keys.

If any of these conditions are violated, an array of error messages will be collected and thrown as a ValidationError.

Parameters:
Name Type Description
schema_doc Object

The schema document to validate.

Properties
Name Type Description
schema Object

The schema structure containing:

Properties
Name Type Description
type String

The type of the schema (must be 'object').

properties Object

The properties defined in the schema.

additionalProperties Boolean

Indicates if additional properties are allowed.

settings Object

The settings associated with the schema, including:

Properties
Name Type Description
primary_keys Array.<String>

List of primary keys for the schema.

non_editable_fields Array.<String>

Fields that cannot be edited.

encrypted_fields Array.<String>

Fields that require encryption.

Throws:

If any validation checks fail, with an array of error messages.

Type
ValidationError