import * as plugins from './smartdata.plugins' import { Objectmap } from 'lik' import { DbTable } from './smartdata.classes.dbcollection' import { getObjectDoc } from './smartdata.classes.dbobjectdoc' import { Connection as dbConnection, ConnectionOptions } from 'rethinkdb' /** * interface - indicates the connection status of the db */ export type TConnectionStatus = 'initial' | 'disconnected' | 'connected' | 'failed' export class Db { dbName: string connectionOptions: plugins.rethinkDb.ConnectionOptions dbConnection: plugins.rethinkDb.Connection status: TConnectionStatus dbTablesMap = new Objectmap>() constructor(connectionOptionsArg: ConnectionOptions) { this.dbName = connectionOptionsArg.db this.connectionOptions = connectionOptionsArg this.status = 'initial' } // basic connection stuff ---------------------------------------------- /** * connects to the database that was specified during instance creation */ async connect (): Promise { this.dbConnection = await plugins.rethinkDb.connect(this.connectionOptions) this.status = 'connected' plugins.beautylog.ok(`Connected to database ${this.dbName}`) } /** * closes the connection to the databse */ async close (): Promise { await this.dbConnection.close() this.status = 'disconnected' plugins.beautylog.ok(`disconnected to database ${this.dbName}`) } // handle table to class distribution /** * Gets a table's name and returns smartdata's DbTable class * @param nameArg * @returns DbTable */ async getDbTableByName(nameArg: string): Promise> { let resultCollection = this.dbTablesMap.find((dbCollectionArg) => { return dbCollectionArg.name === nameArg }) return resultCollection } addTable (dbCollectionArg: DbTable) { this.dbTablesMap.add(dbCollectionArg) } }