Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created August 23, 2023 10:26
Show Gist options
  • Save gtchakama/49ac64e965353ea39fec39e14139d270 to your computer and use it in GitHub Desktop.
Save gtchakama/49ac64e965353ea39fec39e14139d270 to your computer and use it in GitHub Desktop.
NodeJS CRUD With Postgres
const express = require('express');
const { Pool } = require('pg');
const app = express();
const port = process.env.PORT || 3000;
const pool = new Pool({
user: 'your_db_user',
host: 'localhost',
database: 'your_db_name',
password: 'your_db_password',
port: 5432,
});
app.use(express.json());
// Create
app.post('/items', async (req, res) => {
const { name, description } = req.body;
try {
const result = await pool.query(
'INSERT INTO items (name, description) VALUES ($1, $2) RETURNING *',
[name, description]
);
res.json(result.rows[0]);
} catch (error) {
console.error('Error creating item:', error);
res.status(500).json({ error: 'An error occurred.' });
}
});
// Read
app.get('/items', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM items');
res.json(result.rows);
} catch (error) {
console.error('Error fetching items:', error);
res.status(500).json({ error: 'An error occurred.' });
}
});
// Update
app.put('/items/:id', async (req, res) => {
const id = req.params.id;
const { name, description } = req.body;
try {
const result = await pool.query(
'UPDATE items SET name = $1, description = $2 WHERE id = $3 RETURNING *',
[name, description, id]
);
res.json(result.rows[0]);
} catch (error) {
console.error('Error updating item:', error);
res.status(500).json({ error: 'An error occurred.' });
}
});
// Delete
app.delete('/items/:id', async (req, res) => {
const id = req.params.id;
try {
await pool.query('DELETE FROM items WHERE id = $1', [id]);
res.json({ message: 'Item deleted successfully.' });
} catch (error) {
console.error('Error deleting item:', error);
res.status(500).json({ error: 'An error occurred.' });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment