Mike (grind edition πͺ)
Explore posts from serversRRailway
β’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'.
This is the only instance where the class is instantiated
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;
// 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