smartdata/ts/smartdata.classes.db.ts

80 lines
2.3 KiB
TypeScript
Raw Normal View History

2016-09-11 16:01:46 +00:00
import * as plugins from './smartdata.plugins'
2016-09-13 20:53:21 +00:00
import { Objectmap } from 'lik'
2018-01-07 16:26:34 +00:00
import { DbTable } from './smartdata.classes.dbcollection'
2016-09-11 16:01:46 +00:00
2018-01-07 16:26:34 +00:00
import { Connection as dbConnection, ConnectionOptions } from 'rethinkdb'
2016-11-17 11:20:52 +00:00
/**
* interface - indicates the connection status of the db
*/
export type TConnectionStatus = 'initial' | 'disconnected' | 'connected' | 'failed'
2016-09-11 16:01:46 +00:00
2016-09-12 21:47:57 +00:00
export class Db {
2018-01-07 16:26:34 +00:00
dbName: string
connectionOptions: plugins.rethinkDb.ConnectionOptions
dbConnection: plugins.rethinkDb.Connection
2017-02-25 10:37:05 +00:00
status: TConnectionStatus
2018-01-07 16:58:30 +00:00
dbTablesMap = new Objectmap<DbTable<any>>()
2016-09-11 16:01:46 +00:00
2018-01-07 16:58:30 +00:00
constructor(connectionOptionsArg: ConnectionOptions) {
2018-01-07 16:26:34 +00:00
this.dbName = connectionOptionsArg.db
this.connectionOptions = connectionOptionsArg
this.status = 'initial'
2017-02-25 10:37:05 +00:00
}
2016-09-11 16:01:46 +00:00
/**
* supply additional SSl options
*/
setSsl (certificateStringArg: string, formatArg: 'base64' | 'clearText') {
let certificateString: string
if(formatArg = 'base64') {
certificateString = plugins.smartstring.base64.decode(certificateStringArg)
} else {
certificateString = certificateStringArg
}
this.connectionOptions['ssl'] = {
ca: Buffer.from(certificateString)
}
}
2017-02-25 10:37:05 +00:00
// basic connection stuff ----------------------------------------------
2016-09-13 20:53:21 +00:00
2017-02-25 10:37:05 +00:00
/**
* connects to the database that was specified during instance creation
*/
2018-01-07 16:26:34 +00:00
async connect (): Promise<any> {
this.dbConnection = await plugins.rethinkDb.connect(this.connectionOptions)
this.dbConnection.use(this.dbName)
this.status = 'connected'
2018-01-07 16:26:34 +00:00
plugins.beautylog.ok(`Connected to database ${this.dbName}`)
2017-02-25 10:37:05 +00:00
}
2016-09-11 16:01:46 +00:00
2017-02-25 10:37:05 +00:00
/**
* closes the connection to the databse
*/
async close (): Promise<any> {
await this.dbConnection.close()
this.status = 'disconnected'
plugins.beautylog.ok(`disconnected from database ${this.dbName}`)
2017-02-25 10:37:05 +00:00
}
2016-09-13 20:53:21 +00:00
2018-01-07 16:58:30 +00:00
// handle table to class distribution
/**
* Gets a table's name and returns smartdata's DbTable class
* @param nameArg
* @returns DbTable
*/
async getDbTableByName<T>(nameArg: string): Promise<DbTable<T>> {
let resultCollection = this.dbTablesMap.find((dbCollectionArg) => {
return dbCollectionArg.tableName === nameArg
2018-01-07 16:58:30 +00:00
})
return resultCollection
}
addTable (dbCollectionArg: DbTable<any>) {
this.dbTablesMap.add(dbCollectionArg)
}
2016-09-11 16:01:46 +00:00
}