Skip to content

Commit

Permalink
Merge pull request #73 from daeisbae/59-support-ssl-based-db-connection
Browse files Browse the repository at this point in the history
Support SSL based DB connection (#59)
  • Loading branch information
daeisbae authored Jan 1, 2025
2 parents e2c3023 + 33cc3e0 commit 5d9b500
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 58 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ DB_PORT=
DB_NAME=
DB_USER=
DB_PASSWORD=
# if you do not require any certificate, you can ignore this
# if you want to need ssl connection with the DB, place the certificate inside the certificates folder then give the filename of the certificate
DB_CERTIFICATE=

# Github Token for increasing rate limit of reading the repository
GITHUB_TOKEN=
Expand Down
Empty file.
17 changes: 9 additions & 8 deletions src/db/config/config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import dotenv from 'dotenv';
dotenv.config();
import dotenv from 'dotenv'
dotenv.config()

export const DBConfig = {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
};
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
certificate: process.env.DB_CERTIFICATE,
}
109 changes: 64 additions & 45 deletions src/db/scripts/init-db.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,70 @@
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const { Client } = require("pg");
const { readFile } = require("fs/promises");
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { DBConfig } from "../config/config.js";
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const { Client } = require('pg')
const { readFile } = require('fs/promises')
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { DBConfig } from '../config/config.js'
import { promises as fs } from 'fs'

const __dirname = dirname(fileURLToPath(import.meta.url));
const __dirname = dirname(fileURLToPath(import.meta.url))

async function initDatabase() {
console.log("Initializing database with config:", {
host: DBConfig.host,
port: DBConfig.port,
database: DBConfig.database,
user: DBConfig.user,
});

const pgClient = new Client({
...DBConfig,
});
pgClient.connect();

await pgClient
.query(`CREATE DATABASE ${DBConfig.database};`)
.catch((error) => {
console.log("❌ Database is already created");
})
.then(() => {
console.log("✅ Database created successfully");
});

const schemaPath = join(__dirname, "../migrations/create_tables.sql");
const sql = await readFile(schemaPath, "utf8");

await pgClient.query(sql).catch((error) => {
console.error("❌ Schema loading failed:", error);
});
console.log("✅ Schema loaded successfully");
pgClient.end();
console.log('Initializing database with config:', {
host: DBConfig.host,
port: DBConfig.port,
database: DBConfig.database,
user: DBConfig.user,
})

const { certificate, config } = DBConfig

let pgClient = undefined

if (!certificate) {
pgClient = new Client({
...config,
})
} else {
pgClient = new Client({
...config,
ssl: {
rejectUnauthorized: false,
ca: fs
.readFile(process.cwd() + '/certificates/' + certificate)
.toString(),
sslmode: 'require',
},
})
}

pgClient.connect()

await pgClient
.query(`CREATE DATABASE ${DBConfig.database};`)
.catch((error) => {
console.log('❌ Database is already created')
})
.then(() => {
console.log('✅ Database created successfully')
})

const schemaPath = join(__dirname, '../migrations/create_tables.sql')
const sql = await readFile(schemaPath, 'utf8')

await pgClient.query(sql).catch((error) => {
console.error('❌ Schema loading failed:', error)
})
console.log('✅ Schema loaded successfully')
pgClient.end()
}

initDatabase()
.then(() => {
console.log("✅ Database initialization complete");
process.exit(0);
})
.catch((error) => {
console.error("❌ Fatal error:", error);
process.exit(1);
});
.then(() => {
console.log('✅ Database initialization complete')
process.exit(0)
})
.catch((error) => {
console.error('❌ Fatal error:', error)
process.exit(1)
})
15 changes: 10 additions & 5 deletions src/db/utils/connector.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import pg, { QueryResult } from 'pg'
// import { promises as fs } from 'fs'
import {readFileSync} from 'fs'
import { DBConfig } from '@/db/config/config'
import { promises as fs } from 'fs'

Expand All @@ -20,14 +18,21 @@ class DBConnector {
private constructor() {
const { Pool } = pg
this.conn = false
this.pool = new Pool({...DBConfig, ...{
const { certificate, ...config } = DBConfig
if (!certificate) {
this.pool = new Pool(config)
return
}
this.pool = new Pool({
...config,
ssl: {
rejectUnauthorized: false,
ca: fs.readFile(process.cwd() + '/src/assets/ca-certificate.crt')
ca: fs
.readFile(process.cwd() + '/certificates/' + certificate)
.toString(),
sslmode: 'require',
},
}})
})
}

/**
Expand Down

0 comments on commit 5d9b500

Please sign in to comment.