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.

rest_enabled

This is the list of methods that are compatible with JSON-REST API. Each command either has no params or takes just one json param as input

Methods

(async) create(input) → {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 Description
input object

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

Properties
Name Type Attributes Default Description
schema string <optional>

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

data object <optional>
{}

the data for the document.

meta object <optional>
{}

Optional metadata associated with the document.

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) create_edge(node1, node2, edge_name, edge_label) → {Object}

To add an edge between 2 nodes in the system wide simple directed graph.

Parameters:
Name Type Description
node1 object
node2 object
edge_name string
edge_label *
Returns:
Type
Object

(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(inputopt) → {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
input Object <optional>
{}

Criteria used to search for the special document.

Properties
Name Type Attributes Default Description
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>

(async) initialize_app(app_data)

Install/Updates an app in the database. This should be called before using any

Parameters:
Name Type Description
app_data Object

(async) load_plugin(plugin_name, plugin_module)

To load a plugin in the current BeanBagDB instance. Plug_module has to be loaded manually first. It must export an object containing fields: actions and schema. actions is an object of methods which can be called after loading the plugin. schema is an array of JSON schemas that are required by the plugin. Every time a plugin is loaded, this list is schemas is verified. New updates are added automatically to the database and logged methods inside actions must be async and must have at least one parameter : db_instance which is assumed to be the current instance of the BeanBagDB object itself. They ideally must also return some value.

Parameters:
Name Type Description
plugin_name string
plugin_module object

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) modify_setting(name, value, mode)

Check if the setting with the given name exists. New record created if not found. If found data is updated based on the updated_mode and the data type of the existing data If existing value is an array, and update_mode is append "value" is appended to the current value array. if existing value is an object, update_mode "append" will update fields that exists in the new object, for both data types, new value is replaced in update_mode : "replace"

Parameters:
Name Type Description
name string

The name of the setting

value object

Value to be modified

mode string

(async) read(criteria) → {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 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 string <optional>

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>

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(params) → {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 Description
params Object

Object to fetch and update data

Properties
Name Type Attributes Default Description
criteria Object <optional>

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

updates Object <optional>

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

rev_id String <optional>

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

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_filter_object()

Filters an object, returning a new object that only contains the specified fields. const data = { name: "Alice", age: 25, location: "NY" }; const result = util_filter_object(data, ["name", "age"]); // result: { name: "Alice", age: 25 }

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 and returns a valid data object (with default value for missing field for which default values are defined in the 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