Skip to content

Instantly share code, notes, and snippets.

@markodayan
Created July 10, 2020 12:50
Show Gist options
  • Save markodayan/82e7280064d752ded3fe21339e5ee49d to your computer and use it in GitHub Desktop.
Save markodayan/82e7280064d752ded3fe21339e5ee49d to your computer and use it in GitHub Desktop.
Express Server with PostgreSQL CRUD routes
CREATE DATABASE perntodo;
CREATE TABLE todo(
todo_id SERIAL PRIMARY KEY,
description VARCHAR(255)
);
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'postgres',
host: 'localhost',
port: 5432,
database: 'perntodo',
});
module.exports = pool;
const express = require('express');
const cors = require('cors');
const pool = require('./db');
const app = express();
// middleware
app.use(cors());
app.use(express.json()); // req body parser
// routes
// create a todo
app.post('/todos', async (req, res) => {
try {
const { description } = req.body;
const newTodo = await pool.query(
'INSERT INTO todo (description) VALUES ($1) RETURNING *',
[description]
);
res.json(newTodo.rows[0]);
console.log(description);
} catch (err) {
console.log(err.message);
}
});
// get all todos
app.get('/todos', async (req, res) => {
try {
const allTodos = await pool.query('SELECT * FROM todo');
res.json(allTodos.rows);
} catch (err) {
console.log(err.message);
}
});
// get a todo
app.get('/todos/:id', async (req, res) => {
try {
const { id } = req.params;
const todo = await pool.query('SELECT * FROM todo WHERE todo_id = $1', [
id,
]);
res.json(todo.rows[0]);
} catch (err) {
console.log(err.message);
}
});
// update a todo
app.put('/todos/:id', async (req, res) => {
try {
const { id } = req.params;
const { description } = req.body;
const updateTodo = await pool.query(
'UPDATE todo SET description = $1 WHERE todo_id = $2 RETURNING *',
[description, id]
);
res.json(updateTodo.rows[0]);
} catch (err) {
console.log(err.message);
}
});
// delete a todo
app.delete('/todos/:id', async (req, res) => {
try {
const { id } = req.params;
const deleteTodo = await pool.query('DELETE FROM todo WHERE todo_id = $1', [
id,
]);
res.json({ message: 'Todo Deleted' });
} catch (err) {
console.log(err.message);
}
});
app.listen(5000, () => {
console.log('server has started on port 5000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment