DianaDb ODM for Node.js project

Install DianaDb

(DianaDB Server 4.6.5 works with ODM >= 4.0.0; insertMany and the salted handshake need ODM >= 4.6.5)

npm i -s @diana-db/odm
            

Create DianaDb instance

import { readFileSync } from 'node:fs';
import { DianaDb } from '@diana-db/odm';

export const dianaDb = new DianaDb({
  host: 'db.example.com',
  port: 34567, // 1025–65535
  user: 'db_user',
  password: 'some-password',
  connectionPoolSize: 5,
  connectTimeoutValue: 5000,
  reconnectTimeoutValue: 1000,
  requestTimeoutValue: 30000,
  database: 'test', // default database for migrations (optional)
  secureServer: true, // if your server uses TLS
  tls: {
    ca: readFileSync('/path/to/ca'), // CA that signed the server certificate
    cert: readFileSync('/path/to/cert'), // only for mTLS
    key: readFileSync('/path/to/key'), // only for mTLS
  },
});

await dianaDb.connect(5000);
            

A connection string may be used instead:

import { DianaDb } from '@diana-db/odm';

export const dianaDb = new DianaDb('diana-db://user:pass@localhost:34567?connectionPoolSize=5');
// TLS, with "test" as the default database for migrations
export const dianaDbS = new DianaDb('diana-dbs://user:pass@db.example.com:34567/test');
            

The connection string accepts connectionPoolSize, connectTimeoutValue, reconnectTimeoutValue, requestTimeoutValue and legacyAuth as query parameters, and rejectUnauthorized=false with diana-dbs://. The optional path sets the database option. User name and password are URL-decoded, so encode special characters (p%40ss for p@ss). diana-dbs:// sets secureServer: true; any other protocol throws a configuration error.

Connection behaviour

  • connect() resolves as soon as one pooled connection is up; the others connect in the background.
  • If every connection is down (server restart, network blip), new requests are queued and sent when a connection is back, or fail with a TIMEOUT error after requestTimeoutValue.
  • Requests already sent on a connection that drops fail immediately with a CONNECTION error instead of waiting for their timeout.
  • A wrong password fails the request at once with a message naming the likely cause: the server closes connections whose requests it cannot decrypt.
  • After disconnect() requests fail immediately until connect() is called again. disconnect() also closes the subscriber connection, so the Node.js process can exit.

Every failed request rejects with an error carrying a code, see Errors.

DianaDb Constructor Options

PropertyDescriptionFormatDefault Value
hostServer host. RequiredString–
portServer portInteger, 1025–6553534567
userUsername. RequiredString–
passwordPassword. RequiredString–
connectionPoolSizeNumber of pooled connectionsPositive integer5
connectTimeoutValueConnection timeout in millisecondsPositive integer30000
reconnectTimeoutValueDelay between reconnection attempts in millisecondsPositive integer1000
requestTimeoutValueDefault timeout of every request in millisecondsPositive integer30000
database Database used by migrateUp, migrateDown and getMigrations when called without one String–
secureServerWhether the server uses TLSBooleanfalse
tls{ ca?, rejectUnauthorized?, servername?, cert?, key? }. Values are Buffers (readFileSync) or PEM strings; ca may be an array; other Node.js tls.connect options pass through. cert/key are only needed when the server verifies clients (mTLS) Object–
legacyAuth Fall back to the earlier handshake when the server is older than 4.6.5. false refuses such servers. Also accepted as ?legacyAuth=false in a connection string. See SecurityBooleantrue
loggerLogger with log and errorObjectconsole

Client Methods

MethodArgumentsDescriptionReturn Type
connectconnectTimeoutValue?: positive integerConnects to the server. Rejects with a CONNECTION error after the timeoutPromise<boolean>
disconnect–Closes every connection, the subscriber connection included. Pending requests fail at oncePromise<void>
subscribekey: string, subscriber: (update: DatabaseUpdate) => void — SubscribersAdds a subscriber for database or collection changes. Several per key are allowedPromise<void>
unsubscribekey: string, subscriber? Removes one subscriber, or every subscriber of the key. Closes the subscriber connection when none are left Promise<void>
addMigrationmigration: MigrationRegisters a migration script. Throws if its index or name is already usedvoid
migrateUpdatabase?: stringApplies pending migrations in ascending index orderPromise<MigrationInfo[]>
migrateDowndatabase?: string, steps?: numberReverts applied migrations in descending index order — all, or the last stepsPromise<MigrationInfo[]>
getMigrationsdatabase?: stringNames of the migrations recorded as applied on the serverPromise<string[]>
startTransactionStartTransactionParameters: objectStarts a transaction with an optional auto-rollbackPromise<string> (transactionId)
commitTransactionManageTransactionParameters: objectCommits an open transactionPromise<TransactionInfo>
rollbackTransactionManageTransactionParameters: objectRolls back an open transactionPromise<TransactionInfo>
getDatabases–Names of the databases the current user can readPromise<string[]>
createDatabasedatabase: stringCreates an empty database. Requires manage access to itPromise<{ database: string; action: 'created' }>
removeDatabasedatabase: stringRemoves a databasePromise<{ database: string; action: 'removed' }>
getCollectionsdatabase: stringCollection names in a databasePromise<string[]>
createCollectiondatabase: string, collection: string, schema: SchemaCreates a collectionPromise<{ collection: string; action: 'created' }>
removeCollectiondatabase: string, collection: stringRemoves a collectionPromise<{ collection: string; action: 'removed' }>
getCollectionSchemadatabase: string, collection: stringStored schema and its lock statePromise<{ schema: Schema; locked: boolean }>
getCollectionSchemaLockdatabase: string, collection: stringLock state of the schemaPromise<{ collection: string; locked: boolean }>
lockCollectionSchemadatabase: string, collection: stringLocks the schemaPromise<{ collection: string; locked: boolean }>
unlockCollectionSchemadatabase: string, collection: stringUnlocks the schemaPromise<{ collection: string; locked: boolean }>
getCollectionViewsdatabase: string, collection: stringMaterialized views defined on a collectionPromise<Record<string, { transformQueries }>>
getHealth–Current server healthPromise<HealthInfo>
getVersion–Server versionPromise<{ version: string }>
type HealthInfo = {
  memory: number; // memory usage (MB)
  cpu: number;    // CPU usage (%)
  gcp: number;    // garbage collector pressure (%)
  elu: number;    // event loop utilization (%)
  eld: number;    // event loop delay (ms)
};