rbi-learning / Today-I-Learned

1 stars 0 forks source link

8/14 Sara Ho #141

Open saraashleyho opened 4 years ago

saraashleyho commented 4 years ago

Today I Learned

SEQUEL to SQL

CREATE TABLE IF NOT EXISTS tablename

CREATE UNIQUE INDEX IF NOT EXISTS indexname ON tablename (column1, column2);

SERVER SET UP

In the terminal:

In the top of your index.js:


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 });

And at the bottom:

app.listen(PORT, () =>
  console.log(`Server is up and running at port ${PORT} 🚀`)
);

Creating Your Table

Example:

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

CONNECTING THE FRONT END TO THE SERVER

async function voteForDonut(event) {
  const theButtonThatGotClicked = event.currentTarget;
  const theClosestDonut = theButtonThatGotClicked.closest('.donut');
  const donutId = theClosestDonut.dataset.donut;
  const url = '/votes';
  await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify({
      voter: voterId,
      donut: donutId,
    }),
  });
  await tallyVotes();
}

For a full example, reference the "donut of the day" project or the "get things done" project.