refactor(db): centralize database URL configuration by importing dbUrl from constants

This commit is contained in:
Mauricio Siu
2026-01-21 17:33:06 +01:00
parent cbd70fe5d0
commit 9a9e3dc295
8 changed files with 52 additions and 72 deletions

View File

@@ -0,0 +1,39 @@
import fs from "node:fs";
export const {
DATABASE_URL,
POSTGRES_PASSWORD_FILE,
POSTGRES_USER = "dokploy",
POSTGRES_DB = "dokploy",
POSTGRES_HOST = "dokploy-postgres",
POSTGRES_PORT = "5432",
} = process.env;
function readSecret(path: string): string {
try {
return fs.readFileSync(path, "utf8").trim();
} catch {
throw new Error(`Cannot read secret at ${path}`);
}
}
export let dbUrl: string;
if (DATABASE_URL) {
// Compatibilidad legacy / overrides
dbUrl = DATABASE_URL;
} else if (POSTGRES_PASSWORD_FILE) {
const password = readSecret(POSTGRES_PASSWORD_FILE);
dbUrl = `postgres://${POSTGRES_USER}:${encodeURIComponent(
password,
)}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}`;
} else {
console.warn(`
⚠️ [DEPRECATED DATABASE CONFIG]
You are using the legacy hardcoded database credentials.
This mode WILL BE REMOVED in a future release.
Please migrate to Docker Secrets using POSTGRES_PASSWORD_FILE.
Please execute this guide: https://dokploy.com/SECURITY_MIGRATION.md
`);
dbUrl =
"postgres://dokploy:amukds4wi9001583845717ad2@dokploy-postgres:5432/dokploy";
}

View File

@@ -1,5 +1,6 @@
import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { dbUrl } from "./constants";
import * as schema from "./schema";
declare global {
@@ -8,14 +9,16 @@ declare global {
export let db: PostgresJsDatabase<typeof schema>;
if (process.env.NODE_ENV === "production") {
db = drizzle(postgres(process.env.DATABASE_URL!), {
db = drizzle(postgres(dbUrl), {
schema,
});
} else {
if (!global.db)
global.db = drizzle(postgres(process.env.DATABASE_URL!), {
global.db = drizzle(postgres(dbUrl), {
schema,
});
db = global.db;
}
export { dbUrl };

View File

@@ -1,5 +1,6 @@
export * from "./auth/random-password";
export * from "./constants/index";
export * from "./db/constants";
export * from "./db/validations/domain";
export * from "./db/validations/index";
export * from "./lib/auth";