Last active
February 12, 2022 04:04
-
-
Save stevenarellano/0e2dd7da5b271ff031d490769a75b7ee to your computer and use it in GitHub Desktop.
POSTGRES SQL SERVER
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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