Skip to content

Commit

Permalink
best practices
Browse files Browse the repository at this point in the history
  • Loading branch information
hnasr committed Jul 19, 2020
1 parent 23f3e99 commit df82962
Show file tree
Hide file tree
Showing 3 changed files with 165 additions and 15 deletions.
15 changes: 8 additions & 7 deletions express-postgres/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<title>Document</title>
</head>
<body>
<h1>MY BEST TODO APP EVER</h1>
<h1>MY TODO APP</h1>
<ol id = 'olTodo'>

</ol>
Expand All @@ -18,11 +18,11 @@ <h1>MY BEST TODO APP EVER</h1>
btnCreate.addEventListener("click", async e=> {
const jsonRequest = {}
jsonRequest.todo = prompt("Enter your todo item!")
const result = await fetch("http://localhost:8080/todos", {method: "POST",
let result = await fetch("http://localhost:8080/todos", {method: "POST",
headers: {"content-type": "application/json"}, body: JSON.stringify(jsonRequest) })
const success = await result.json();
result = await result.json();
readTodos()
alert("CREATED! ")
if (!result.success) alert("FAILED! ")

})
readTodos();
Expand All @@ -42,11 +42,12 @@ <h1>MY BEST TODO APP EVER</h1>
li.addEventListener("click", async e => {
const jsonRequest = {}
jsonRequest.id = e.target.id;
const result = await fetch("http://localhost:8080/todos", {method: "DELETE",
let result = await fetch("http://localhost:8080/todos", {method: "DELETE",
headers: {"content-type": "application/json"}, body: JSON.stringify(jsonRequest) })
const success = await result.json();
result = await result.json();
readTodos();
alert("Deleted! ")
if (!result.success) alert("FAILED! ")

})
olTodo.appendChild(li)
})
Expand Down
149 changes: 149 additions & 0 deletions express-postgres/newserver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
//using pool is better for web apps so that we can
//reserve a client connection for each request and
//avoid problems with concurrent requests..
//Check out this video I discuss this in details
//https://www.youtube.com/watch?v=GTeCtIoV2Tw
//I Changed all the singelton clients in this code to Pool

const {Pool} = require("pg")
const express = require ("express")
const app = express();
app.use(express.json())

const dbReadPool = new Pool({
"user": "dbread",
"password" : "dbread",
"host" : "husseinmac",
"port" : 5432,
"database" : "todo"
})


const dbDeletePool = new Pool({
"user": "dbdelete",
"password" : "dbdelete",
"host" : "husseinmac",
"port" : 5432,
"database" : "todo"
})


const dbCreatePool = new Pool({
"user": "dbcreate",
"password" : "dbcreate",
"host" : "husseinmac",
"port" : 5432,
"database" : "todo"
})

app.get("/", (req, res) => res.sendFile(`${__dirname}/index.html`))

app.get("/todos", async (req, res) => {
const rows = await readTodos();
res.setHeader("content-type", "application/json")
res.send(JSON.stringify(rows))
})



app.post("/todos", async (req, res) => {
let result = {}
try{
const reqJson = req.body;
result.success = await createTodo(reqJson.todo)
}
catch(e){
result.success=false;
}
finally{
res.setHeader("content-type", "application/json")
res.send(JSON.stringify(result))
}

})





app.delete("/todos", async (req, res) => {
let result = {}
try{

const reqJson = req.body;
result.success = await deleteTodo(reqJson.id)
}
catch(e){
result.success=false;
}
finally{
res.setHeader("content-type", "application/json")
res.send(JSON.stringify(result))
}

})


app.listen(8080, () => console.log("Web server is listening.. on port 8080"))

start()

async function start() {
await connect();
/*
const todos = await readTodos();
console.log(todos)
const successCreate = await createTodo("Go to trader joes")
console.log(`Creating was ${successCreate}`)
const successDelete = await deleteTodo(1)
console.log(`Deleting was ${successDelete}`)
*/
}

async function connect() {
try {
await dbCreatePool.connect();
await dbDeletePool.connect();
await dbReadPool.connect();
}
catch(e) {
console.error(`Failed to connect ${e}`)
}
}

async function readTodos() {
try {
const results = await dbReadPool.query("select id, text from todos");
return results.rows;
}
catch(e){
return [];
}
}

async function createTodo(todoText){

try {
await dbCreatePool.query("insert into todos (text) values ($1)", [todoText]);
return true
}
catch(e){
return false;
}
}



async function deleteTodo(id){

try {
await dbDeletePool.query("delete from todos where id = $1", [id]);
return true
}
catch(e){
return false;
}
}

16 changes: 8 additions & 8 deletions express-postgres/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const pool = new Pool({
"database" : "todo"
})


app.get("/", (req, res) => res.sendFile(`${__dirname}/index.html`))

app.get("/todos", async (req, res) => {
Expand All @@ -31,10 +32,8 @@ app.get("/todos", async (req, res) => {
app.post("/todos", async (req, res) => {
let result = {}
try{

const reqJson = req.body;
await createTodo(reqJson.todo)
result.success= true;
result.success = await createTodo(reqJson.todo)
}
catch(e){
result.success=false;
Expand All @@ -55,8 +54,7 @@ app.delete("/todos", async (req, res) => {
try{

const reqJson = req.body;
await deleteTodo(reqJson.id)
result.success= true;
result.success = await deleteTodo(reqJson.id)
}
catch(e){
result.success=false;
Expand Down Expand Up @@ -90,6 +88,8 @@ async function start() {
async function connect() {
try {
await pool.connect();
await pool.connect();
await pool.connect();
}
catch(e) {
console.error(`Failed to connect ${e}`)
Expand All @@ -98,7 +98,7 @@ async function connect() {

async function readTodos() {
try {
const results = await pool.query("select id, text from todos");
const results = await postgres.query("select id, text from todos");
return results.rows;
}
catch(e){
Expand All @@ -109,7 +109,7 @@ async function readTodos() {
async function createTodo(todoText){

try {
await pool.query("insert into todos (text) values ($1)", [todoText]);
await postgres.query("insert into todos (text) values ($1)", [todoText]);
return true
}
catch(e){
Expand All @@ -122,7 +122,7 @@ async function createTodo(todoText){
async function deleteTodo(id){

try {
await pool.query("delete from todos where id = $1", [id]);
await postgres.query("delete from todos where id = $1", [id]);
return true
}
catch(e){
Expand Down

0 comments on commit df82962

Please sign in to comment.