Skip to content

Instantly share code, notes, and snippets.

@stevenarellano
Last active February 12, 2022 04:04
Show Gist options
  • Save stevenarellano/0e2dd7da5b271ff031d490769a75b7ee to your computer and use it in GitHub Desktop.
Save stevenarellano/0e2dd7da5b271ff031d490769a75b7ee to your computer and use it in GitHub Desktop.
POSTGRES SQL SERVER
// postgress library connection creating a pool
const { Pool } = require("pg");
function createPool() {
const CONFIG = {
// user information
user: "USER",
// host information
host: "HOST",
// database information
database: "DB",
// database password
password:
"PW",
// port information
port: 0000,
// ssl information
ssl: {
rejectUnauthorized: false,
},
};
const pool = new Pool(CONFIG);
return pool;
}
function pgConnect(pool) {
pool.connect((err, client, release) => {
if (err) {
return console.error("Error connecting to db client", err.stack);
}
client.query("SELECT NOW()", (err, result) => {
release();
if (err) {
return console.error("Error executing query", err.stack);
}
console.log(result.rows);
});
});
}
// can also modify it to be handled like readQuery
function insertQuery(pool, query) {
pool.query("SELECT NOW()", (err, result) => {
if (err) {
return console.error("Error executing query", err.stack);
}
console.log(result.rows);
});
}
// function to read a query, seems simple enough
// when using, you must import it, and then handle it with
// .then((res, err) => { ... });
function readQuery(pool, query) {
return pool.query("SELECT NOW()");
}
module.exports = { createPool, pgConnect, insertQuery, readQuery };
// Basic imports for running the server
const express = require("express");
const app = express();
// module functions
const {
createPool,
pgConnect,
insertQuery,
readQuery,
} = require("./db/db");
// connecting to the postgress DB server
let pool = createPool();
pgConnect(pool);
// Run the Server
app.get("/", (req, res) => {
res.send("Server Connected!");
});
// Connect to the Server
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log("running at port: " + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment