-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbe_services.js
63 lines (53 loc) · 1.37 KB
/
be_services.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
const key = "employees";
async function findAll() {
try {
return JSON.parse(localStorage.getItem(key));
} catch (e) {
return [];
}
}
async function addEmployee(employee) {
if (!employee || !employee.username || !employee.password)
throw new Error("Bad Request!");
const id = Date.now();
const employeeObject = { ...employee, id, role: "User" };
const employees = await findAll();
const match = employees.find(
(emp) => emp.email === employee.email || emp.username === employee.username
);
if (match)
throw new Error(
match.email === employee.email
? "Email Already Exist!"
: "Username Already Exist!"
);
employees.push(employeeObject);
localStorage.setItem(key, JSON.stringify(employees));
return employeeObject;
}
async function findBy(criteria) {
const employees = await findAll();
const criteriaKeys = criteria ? Object.keys(criteria) : [];
if (!criteriaKeys.length) throw new Error("Criteria is required!");
return employees.find((emp) =>
criteriaKeys.every((cKey) => criteria[cKey] === emp[cKey])
);
}
if (!localStorage.getItem(key)) {
const seed = [
{
username: "admin",
dob: "",
email: "",
id: 0,
password: "",
role: "Super Admin",
},
];
localStorage.setItem(key, JSON.stringify(seed));
}
export default {
findAll,
findBy,
addEmployee,
};