-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (55 loc) · 1.67 KB
/
server.js
File metadata and controls
72 lines (55 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const express = require('express');
const bodyParser = require('body-parser');
const { Pool } = require('pg');
const app = express();
const port = process.env.PORT || 3001;
const pool = new Pool({
url: 'postgres://rutwgkkq:cXxE1qm9JAXDhWVh672U6dzq1d_Kyf0X@berry.db.elephantsql.com/rutwgkkq',
port: 5432,
});
app.use(bodyParser.json());
app.get('/animals', async (req, res) => {
try {
const { rows } = await pool.query('SELECT * FROM Animal');
res.json(rows);
} catch (error) {
console.error('Error getting animals:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/animals', async (req, res) => {
const { name, species, age } = req.body;
try {
const { rows } = await pool.query(
'INSERT INTO Animal (Name, Species, Age) VALUES ($1, $2, $3) RETURNING *',
[name, species, age]
);
res.json(rows[0]);
} catch (error) {
console.error('Error adding animal:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/animals/:id', async (req, res) => {
const animalID = req.params.id;
try {
const { rows } = await pool.query('SELECT * FROM Animal WHERE AnimalID = $1', [
animalID,
]);
if (rows.length === 0) {
res.status(404).json({ error: 'Animal not found' });
} else {
res.json(rows[0]);
}
} catch (error) {
console.error('Error getting animal by ID:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.put('/animals/:id', async (req, res) => {
});
app.delete('/animals/:id', async (req, res) => {
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});