-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
113 lines (102 loc) · 2.51 KB
/
app.js
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
let express = require("express");
let app = express();
let bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
let port = process.env.port || 3000;
let router = express.Router();
app.use("/api/student", router);
app.listen(port, () => {
console.log(`Node.js application running on port : ${port}`);
});
let students = [
{
StudentId: 1,
FirstName: "Jalpesh",
LastName: "Vadgama",
Gender: "Male",
},
{
StudentId: 2,
FirstName: "Vishal",
LastName: "Vadgama",
Gender: "Male",
},
];
//Get all students
router.get("/", (req, res) => {
res.json(students);
});
//Get students based on id
router.get("/:Id", (req, res) => {
let id = parseInt(req.params.Id);
let currentStudent = students.filter((x) => x.StudentId == id)[0];
if (currentStudent) {
res.json(currentStudent);
} else {
res.sendStatus(404);
}
});
ValidateStudent = (student) => {
let message = "";
if (!student.StudentId) {
message = "Student id not found";
}
if (!student.FirstName) {
message = "Student firstname not found";
}
if (!student.LastName) {
message = "Student lastname not found";
}
if (!student.Gender) {
message = "Student gender not found";
}
return message;
};
//Create student
router.post("/", (req, res) => {
let student = req.body;
let isValid = ValidateStudent(student);
if (isValid == "") {
students.push(student);
console.log(students);
res.status(201).send(students);
} else {
res.statusMessage = isValid;
res.sendStatus(404);
}
});
router.put("/:Id", (req, res) => {
let studentId = req.params.Id;
let student = req.body;
let currentStudent = students.filter((x) => x.StudentId == studentId)[0];
if (currentStudent) {
let isValid = ValidateStudent(student);
if (isValid == "") {
currentStudent.FirstName = student.FirstName;
currentStudent.LastName = student.LastName;
currentStudent.Gender = student.Gender;
res.status(200).send(students);
} else {
res.statusMessage = isValid;
res.sendStatus(404);
}
} else {
res.statusMessage = "Student does not exist";
res.sendStatus(404);
}
});
//Delete API
router.delete("/:Id", (req, res) => {
let studentId = req.params.Id;
let currentStudent = students.filter((x) => x.StudentId == studentId)[0];
if (currentStudent) {
students = students.filter((x) => x.StudentId !== studentId);
console.log(students);
res.statusMessage = "Student deleted sucessfully.";
res.sendStatus(200);
} else {
res.statusMessage = "Student does not exist";
res.sendStatus(404);
}
});