Skip to content

Commit

Permalink
Create Thunder database if not exists
Browse files Browse the repository at this point in the history
  • Loading branch information
micahmo committed May 10, 2024
1 parent c41afe9 commit 4807ace
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/database/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,29 @@ import { Sequelize } from "sequelize";
import dotenv from "dotenv";
dotenv.config();

// Configure database
const sequelize = new Sequelize(
`postgres://${process.env.POSTGRES_USER ?? "user"}:${process.env.POSTGRES_PASSWORD ?? "password"}@${process.env.POSTGRES_HOSTNAME ?? "postgres"}:${process.env.POSTGRES_PORT ?? "5432"}/${process.env.POSTGRES_DATABASE ?? "thunder-database"}`
// Connect to the default Postgres db
var sequelize = new Sequelize(
`postgres://${process.env.POSTGRES_USER ?? "user"}:${process.env.POSTGRES_PASSWORD ?? "password"}@${process.env.POSTGRES_HOSTNAME ?? "postgres"}:${process.env.POSTGRES_PORT ?? "5432"}/postgres`
);

// Connect to a default database
sequelize.authenticate()
.then(async () => {
const thunderDatabase = process.env.POSTGRES_DATABASE ?? "thunder-database";

// Check if the Thunder database exists
const result = await sequelize.query(`SELECT FROM pg_database WHERE datname = '${thunderDatabase}'`);
const exists = result[0].length > 0;

// Create if not
if (!exists) {
await sequelize.query(`CREATE DATABASE ${thunderDatabase}`);
}

// Connect to the Thunder database
sequelize = new Sequelize(
`postgres://${process.env.POSTGRES_USER ?? "user"}:${process.env.POSTGRES_PASSWORD ?? "password"}@${process.env.POSTGRES_HOSTNAME ?? "postgres"}:${process.env.POSTGRES_PORT ?? "5432"}/${thunderDatabase}}`
);
});

export default sequelize;

0 comments on commit 4807ace

Please sign in to comment.