Connecting to PostgreSQL
Our database file contains functions and configuration for initializing the Postgres pool, creating tables and running queries.
At the moment, we have only one query. It is a single-use query that creates a products table to the database if such table does not yet exist.
import pg from "pg";
const { PG_HOST, PG_PORT, PG_USERNAME, PG_PASSWORD, PG_DATABASE } = process.env;
const pool = new pg.Pool({
host: PG_HOST,
port: Number(PG_PORT),
user: PG_USERNAME,
password: PG_PASSWORD,
database: PG_DATABASE,
});
const executeQuery = async (query: string, parameters?: Array<any>) => {
const client = await pool.connect();
try {
const result = await client.query(query, parameters);
return result;
} catch (error: any) {
console.error(error.stack);
error.name = "dbError";
throw error;
} finally {
client.release();
}
};
export const createProductsTable = async () => {
const query = `CREATE TABLE IF NOT EXISTS "products" (
"id" SERIAL PRIMARY KEY,
"name" VARCHAR(100) NOT NULL,
"price" REAL NOT NULL
)`;
await executeQuery(query);
console.log("Products table initialized");
};