-
Notifications
You must be signed in to change notification settings - Fork 7
/
MockApi.js
71 lines (63 loc) · 2.2 KB
/
MockApi.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
export default class MockApi {
constructor(defaultUsers = [], latency = 500) {
this.defaultUsers = defaultUsers;
this.latency = latency;
this.setUsers(defaultUsers);
}
getAllUsers() {
let users = JSON.parse(localStorage.getItem('mockApiUsers'));
if (!Array.isArray(users)) {
users = Array(users);
}
return users;
}
setUsers(users) {
if (!Array.isArray(users)) {
users = Array(users);
}
return localStorage.setItem('mockApiUsers', JSON.stringify(users));
}
signInUser(username, password) {
return new Promise(resolve => {
setTimeout(() => {
let apiUsers = [];
apiUsers = this.getAllUsers();
let user = apiUsers.find((user) => user.username === username);
if (user) {
resolve({ error: true, message: 'There is a user who have same credentials' });
} else {
apiUsers.push({ username, password });
this.setUsers(apiUsers);
resolve({ error: false });
}
}, this.latency);
});
}
authenticate(username, password) {
let users = this.getAllUsers();
if (users.length === 0) {
throw new Error('Empty User Store');
}
return new Promise((resolve, reject) => {
setTimeout(() => {
users = this.getAllUsers();
let user = users.find((user) => user.username === username && user.password === password);
if (user) {
resolve({ error: false, data: users });
} else {
resolve({ error: true, data: 'Invalid User Credentials' });
}
}, this.latency);
});
}
checkAuthenticate() {
const email = localStorage.getItem('email');
const password = localStorage.getItem('password');
const users = this.getAllUsers();
let user = users.find((user) => user.username === email && user.password === password);
if (user) {
return true;
}
return false;
}
}