-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
70 lines (62 loc) · 2.13 KB
/
Copy pathserver.js
File metadata and controls
70 lines (62 loc) · 2.13 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
const express = require("express");
const bodyParser = require("body-parser");
const { insertStudent, fetchStudents, deleteStudent, updateStudent, getStudentById } = require("./backend/dynamoOperations");
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
// Route to fetch all students
app.get("/api/students", async (req, res) => {
try {
const students = await fetchStudents();
res.json(students);
} catch (err) {
res.status(500).json({ error: "Error fetching students" });
}
});
// Route to fetch a single student by ID
app.get("/api/students/:id", async (req, res) => {
try {
const student = await getStudentById(req.params.id);
if (student) {
res.json(student);
} else {
res.status(404).json({ error: "Student not found" });
}
} catch (err) {
res.status(500).json({ error: "Error fetching student" });
}
});
// Route to insert a new student
app.post("/api/students", async (req, res) => {
try {
await insertStudent(req.body);
res.status(201).json({ message: "Student added successfully" });
} catch (err) {
res.status(500).json({ error: "Error adding student" });
}
});
// Route to update a student
app.put('/api/students/:id', async (req, res) => {
const studentID = req.params.id;
const updatedData = req.body;
try {
await updateStudent(studentID, updatedData);
res.status(200).json({ message: "Student updated successfully" });
} catch (error) {
console.error("Error updating student: ", error);
res.status(500).json({ error: "Error updating student" });
}
});
// Route to delete a student
app.delete("/api/students/:id", async (req, res) => {
try {
await deleteStudent(req.params.id);
res.json({ message: "Student deleted successfully" });
} catch (err) {
res.status(500).json({ error: "Error deleting student" });
}
});
// Start the server
app.listen(3000, () => {
console.log("Server is running on port 3000");
});