rbi-learning / Today-I-Learned

1 stars 0 forks source link

Today I Learned 8/14 #140

Open amatheus000 opened 4 years ago

amatheus000 commented 4 years ago

Morning Exercise

We worked with databases in fiddle using SQL. We created a table and added rows and values to the table suign SQL commands.

Some of the commands learned:

  1. Current Date: date DATE DEFAULT CURRENT_DATE

  2. Giving a. unique property to one of the tables column. CREATE UNIQUE INDEX unique_voter ON votes (voter, date)

Notes: Important to call out that we can choose all the table's columns we need to show by using

select * from TABLE

Afternoon Exercise

We built the donut voter in sections.

  1. First starting with the back end section using the following code:

const PORT = process.env.PORT || 3000; const express = require('express'); const pg = require('pg'); const app = express(); app.use(express.static('public')); app.use(express.json()); const db = new pg.Pool({ connectionString: process.env.DATABASE_URL }); . . . . db.query( CREATE TABLE IF NOT EXISTS votes( id SERIAL PRIMARY KEY, donut VARCHAR(128) NOT NULL, voter VARCHAR(128) NOT NULL, date DATE DEFAULT CURRENT_DATE NOT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS duplicate_votes_per_day ON votes(voter, date); ); app.listen(PORT, () => console.log(Server is up and running at port ${PORT} 🚀) );

  1. Then we worked in the connection of the Back End to the front woking on donut JS in the public folder using:

function renderDonut(donut) { const html = `

${donut.name}

${donut.votes}

`;

const fragment = document.createRange().createContextualFragment(html); const button = fragment.querySelector('button'); button.addEventListener('click', voteForDonut); return fragment;

  1. We then connected linked teh code to teh database using:

app.get('/votes', async (_request, response) => { const result = await db.query( SELECT * FROM votes WHERE date = CURRENT_DATE; ); response.json(result.rows); });

app.post('/votes', async function(request, response) { const { voter, donut } = request.body; if (!voter || !donut) { response.status(406).json({ error: 'voter and donut requried' }); } else { await db.query( DELETE FROM votes WHERE voter = $1 AND date = CURRENT_DATE;, [voter] ); const result = await db.query( INSERT INTO votes (donut, voter) VALUES ($1, $2) RETURNING *;, [donut, voter] ); response.json(result.rows[0]); } });