-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.js
99 lines (88 loc) · 2.3 KB
/
api.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
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.port || 3000;
var router = express.Router();
app.use('/api/employee', router);
app.listen(port);
var employees= [
{
Id: 1,
FirstName: "Jalpesh",
LastName: "Vadgama",
Designation: "Technical Architect"
}
];
// Get all employees
router.get("/",function (req,res){
res.json(employees);
});
//get specific employee based on Id
router.get("/:Id",function(req,res){
var employeeId = parseInt(req.params.Id);
var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];
if(currentEmployee){
res.json(currentEmployee);
}else{
res.sendStatus(404);
}
});
/// Add employee
router.post("/", function (req,res) {
var employee = req.body;
var isValid =isValidEmployee(employee);
if(isValid){
employees.push(employee);
res.send(employee);
} else{
res.sendStatus(500);
}
});
//Update employee
router.put("/:Id",function (req,res) {
var employeeId = parseInt(req.params.Id);
var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];
if(currentEmployee){
let employee = req.body;
var isValid = isValidEmployee(employee);
if(isValid){
currentEmployee.FirstName = employee.FirstName;
currentEmployee.LastName = employee.FirstName;
currentEmployee.Designation = employee.Designation;
res.sendStatus(204);
}else{
res.sendStatus(500);
}
}else{
res.sendStatus(404);
}
});
//delete employee
router.delete("/:Id", function(req,res){
var employeeId = parseInt(req.params.Id);
var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];
if(currentEmployee){
employees = employees.filter(e=>e.Id!=employeeId);
res.sendStatus(204);
}else{
res.sendStatus(404);
}
});
//validation for employee
function isValidEmployee(employee){
if(!employee.Id){
return false;
}
if(!employee.FirstName){
return false;
}
if(!employee.LastName){
return false;
}
if(!employee.Designation){
return false;
}
return true;
}