Mike  (grind edition πŸ’ͺ)
Mike (grind edition πŸ’ͺ)
Explore posts from servers
RRailway
Created by Mike (grind edition πŸ’ͺ) on 1/28/2024 in #βœ‹ο½œhelp
Do I need the PG package in this case?
I am making an api, was wondering is there and object oriented approach to this in which instead of using 'sequelize-typescript' i could use 'pg'.
import { Sequelize } from "sequelize-typescript";
import { Users } from "../models/Users";
import { Links } from "../models/LinksModel";

class Database {
public sequelize: Sequelize | undefined;

private POSTGRES_DB = process.env.POSTGRES_DATABASE as string;
private POSTGRES_HOST = process.env.POSTGRES_HOST as string;
private POSTGRES_PORT = process.env.POSTGRES_PORT as unknown as number;
private POSTGRES_USER = process.env.POSTGRES_USER as string;
private POSTGRES_PASSWORD = process.env.POSTGRES_PASSWORD as string;

constructor() {
this.connectToPostgreSQL();
}

private async connectToPostgreSQL() {
this.sequelize = new Sequelize({
database: this.POSTGRES_DB,
username: this.POSTGRES_USER,
password: this.POSTGRES_PASSWORD,
host: this.POSTGRES_HOST,
port: this.POSTGRES_PORT,
dialect: "postgres",
models:[Links, Users]
});

await this.sequelize
.authenticate()
.then(() => {
console.log(
"βœ… PostgreSQL Connection has been established successfully."
);
})
.catch((err: any) => {
console.log("❌ Unable to connect to the PostgreSQL database:", err);
});
}
}

export default Database;
import { Sequelize } from "sequelize-typescript";
import { Users } from "../models/Users";
import { Links } from "../models/LinksModel";

class Database {
public sequelize: Sequelize | undefined;

private POSTGRES_DB = process.env.POSTGRES_DATABASE as string;
private POSTGRES_HOST = process.env.POSTGRES_HOST as string;
private POSTGRES_PORT = process.env.POSTGRES_PORT as unknown as number;
private POSTGRES_USER = process.env.POSTGRES_USER as string;
private POSTGRES_PASSWORD = process.env.POSTGRES_PASSWORD as string;

constructor() {
this.connectToPostgreSQL();
}

private async connectToPostgreSQL() {
this.sequelize = new Sequelize({
database: this.POSTGRES_DB,
username: this.POSTGRES_USER,
password: this.POSTGRES_PASSWORD,
host: this.POSTGRES_HOST,
port: this.POSTGRES_PORT,
dialect: "postgres",
models:[Links, Users]
});

await this.sequelize
.authenticate()
.then(() => {
console.log(
"βœ… PostgreSQL Connection has been established successfully."
);
})
.catch((err: any) => {
console.log("❌ Unable to connect to the PostgreSQL database:", err);
});
}
}

export default Database;
This is the only instance where the class is instantiated
// add database sync
protected databaseSync (): void {
const db = new Database()
db.sequelize?.sync()
}
// add database sync
protected databaseSync (): void {
const db = new Database()
db.sequelize?.sync()
}
6 replies