Skip to content

Commit

Permalink
Bootcamp Day 7
Browse files Browse the repository at this point in the history
  • Loading branch information
nbkhope committed Jun 27, 2024
1 parent 46edf1c commit f62a171
Show file tree
Hide file tree
Showing 5 changed files with 1,303 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
.DS_Store
node_modules/
.env
secrets.json
65 changes: 65 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const express = require('express');
const pg = require('pg')
const cors = require('cors');

const secrets = require('./secrets.json');

const app = express();

app.use(cors())
app.use(express.json())

async function setupApp() {
const pgClient = new pg.Client({
database: secrets.DATABASE_NAME,
user: secrets.DATABASE_USER,
password: secrets.DATABASE_PASSWORD,
});
await pgClient.connect();

// HTTP: method (GET or POST...)
// GET /messages
app.get('/messages', function(req, res) {
pgClient.query('SELECT * FROM messages;').then((result) => {
return res.send(result.rows);
});
});

app.post('/messages', async function(req, res) {
// consider usually doing beforehand:
// 1) filter out undesired properties
// 2) validate the supplied request information
const newMessage = req.body;

// if authenticated, usually you'd get something like:
// req.user
const author = { id: '123', username: 'fakeuser' };

try {
const result = await pgClient.query(`INSERT INTO messages (comment, author_id, created_at) VALUES ($1, $2, $3) RETURNING *`, [newMessage.comment, author.id, new Date()])

return res.send(result.rows[0]);
}
catch (error) {
// report error somewhere
console.error(error);
return res.status(500).send({ error: 'Internal Server Error' });
}

});

// REST naming CONVENTION for endpoint paths:
// retrieve all things: GET /resource
// retrieve one thing: GET /resource/:resourceId (express req.params.resourceId)
// delete one thing: DELETE /resource/:resourceId
// update one thing: PUT /resource/:resourceId
// partial update thing: PATCH /resource/:resourceId
// create one thing: POST /resource

const port = 3001;
app.listen(port, function() {
console.log(`Server is running at http://localhost:${port}`);
});
}

setupApp();
Loading

0 comments on commit f62a171

Please sign in to comment.