Skip to content

Commit

Permalink
feat: Update the Rethink adapter to auto-setup a database.
Browse files Browse the repository at this point in the history
  • Loading branch information
vxern committed Oct 5, 2024
1 parent 8edd0ac commit 30bd5a5
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions source/library/adapters/databases/rethinkdb/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import rethinkdb from "rethinkdb-ts";

class RethinkDBAdapter extends DatabaseAdapter {
readonly #connectionOptions: rethinkdb.RConnectionOptions;
readonly #databaseName: string;
#connection!: rethinkdb.Connection;

constructor({
Expand All @@ -30,7 +31,8 @@ class RethinkDBAdapter extends DatabaseAdapter {
}) {
super({ identifier: "RethinkDB", log });

this.#connectionOptions = { host, port: Number(port), db: database, user: username, password };
this.#connectionOptions = { host, port: Number(port), user: username, password, silent: true };
this.#databaseName = database;
}

static tryCreate({
Expand Down Expand Up @@ -59,7 +61,30 @@ class RethinkDBAdapter extends DatabaseAdapter {
}

async setup(): Promise<void> {
this.#connection = await rethinkdb.r.connect(this.#connectionOptions);
try {
this.#connection = await rethinkdb.r.connect(this.#connectionOptions);
} catch (error: any) {
this.log.error(error, `Failed to connect to database '${this.#connectionOptions.db}'.`);
throw error;
}

const databases = await rethinkdb.r.dbList().run(this.#connection);
const databaseExists = databases.includes(this.#databaseName);
if (!databaseExists) {
this.log.info(`The database '${this.#databaseName}' does not exist. Creating...`);

try {
await rethinkdb.r.dbCreate(this.#databaseName).run(this.#connection);
} catch (error: any) {
this.log.error(error, `Could not create database '${this.#databaseName}'.`);
throw error;
}

this.log.info(`Created database '${this.#databaseName}'.`);
}

this.#connection.use(this.#databaseName);

await this.#createMissingTables();
}

Expand Down

0 comments on commit 30bd5a5

Please sign in to comment.