@laiyon/create-wasapi
Version:
CLI to create WhatsApp bot projects with Wasapi and BuilderBot
92 lines (91 loc) • 2.69 kB
JavaScript
export class PostgreSQLProvider {
createDatabase(config) {
return new PostgreSQLDatabase(config);
}
getRequiredEnvVars() {
return ["POSTGRES_DB_HOST", "POSTGRES_DB_USER", "POSTGRES_DB_NAME", "POSTGRES_DB_PASSWORD"];
}
validateConfig(config) {
return !!(config.host && config.user && config.database);
}
// Optimized method for quick validation
async validateConnection(config) {
let client = null;
try {
// Dynamic import - only load pg when needed
const { Client } = await import("pg");
client = new Client({
host: config.host,
port: config.port || 5432,
user: config.user,
password: config.password,
database: config.database,
connectionTimeoutMillis: 5000
});
await client.connect();
await client.query('SELECT 1');
return true;
}
catch (error) {
return false;
}
finally {
if (client) {
await client.end();
}
}
}
}
class PostgreSQLDatabase {
constructor(config) {
this.client = null;
this.connected = false;
this.config = config;
}
async connect() {
try {
// Dynamic import - only load pg when needed
const { Client } = await import("pg");
this.client = new Client({
host: this.config.host,
port: this.config.port || 5432,
user: this.config.user,
password: this.config.password,
database: this.config.database
});
await this.client.connect();
this.connected = true;
console.log(`✅ Connected to PostgreSQL on ${this.config.host}:${this.config.port || 5432}`);
}
catch (error) {
this.connected = false;
throw new Error(`Error connecting to PostgreSQL: ${error}`);
}
}
async disconnect() {
if (this.client) {
await this.client.end();
this.client = null;
}
this.connected = false;
console.log("🔌 Disconnected from PostgreSQL");
}
isConnected() {
return this.connected;
}
getConfig() {
return { ...this.config };
}
async testConnection() {
try {
if (this.client) {
await this.client.query('SELECT 1');
return true;
}
return false;
}
catch {
return false;
}
}
}