smartdata/ts/smartdata.classes.db.ts

86 lines
2.4 KiB
TypeScript
Raw Normal View History

import * as plugins from "./smartdata.plugins";
import { Objectmap } from "lik";
2016-09-13 20:53:21 +00:00
import { DbTable } from "./smartdata.classes.dbtable";
2016-09-11 16:01:46 +00:00
import { Connection as dbConnection, ConnectionOptions } from "rethinkdb";
2018-01-07 16:26:34 +00:00
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 {
dbName: string;
connectionOptions: plugins.rethinkDb.ConnectionOptions;
dbConnection: plugins.rethinkDb.Connection;
status: TConnectionStatus;
dbTablesMap = new Objectmap<DbTable<any>>();
2016-09-11 16:01:46 +00:00
2018-01-07 16:58:30 +00:00
constructor(connectionOptionsArg: ConnectionOptions) {
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 needed to connect to certain Rethink DB servers (e.g. compose.io)
*/
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
*/
async connect(): Promise<any> {
this.dbConnection = await plugins.rethinkDb.connect(this.connectionOptions);
this.dbConnection.use(this.dbName);
this.status = "connected";
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
addTable(dbTableArg: DbTable<any>) {
this.dbTablesMap.add(dbTableArg);
}
2018-01-07 16:58:30 +00:00
/**
* 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(dbTableArg => {
return dbTableArg.tableName === nameArg;
});
return resultCollection;
2018-01-07 16:58:30 +00:00
}
2016-09-11 16:01:46 +00:00
}