-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain-of-responsibility.ts
81 lines (60 loc) · 2.22 KB
/
chain-of-responsibility.ts
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
const userFakes = [{username: "[email protected]", password: "abc123"}, {username: "[email protected]", password: "abc123"}]
interface Middleware {
setNext(middleware: Middleware): Middleware;
handle(username: string, password: string): string;
}
abstract class AbstractMiddleware implements Middleware
{
private next: Middleware;
public setNext(middleware: Middleware): Middleware {
this.next = middleware;
return middleware;
}
public handle(username: string, password: string): string {
if (this.next) {
return this.next.handle(username, password);
}
return '';
}
}
class CheckValidPayload extends AbstractMiddleware {
public handle(username: string, password: string): string {
if (username.length < 6 || password.length < 6) {
return `Username or Password must be greater than 6 charactor.`;
}
return super.handle(username, password);
}
}
class CheckEmailExits extends AbstractMiddleware {
public handle(username: string, password: string): string {
const users = userFakes.filter((x) => x.username === username);
if (!users.length) {
return `Username not exits.`;
}
return super.handle(username, password);
}
}
class Login extends AbstractMiddleware {
public handle(username: string, password: string): string {
const users = userFakes.filter((x) => x.username === username);
if (!users.length) {
return `User is not exits.`;
}
const user = users[0];
if (user.password !== password) {
return `The password is incorrect. Try again`;
}
return JSON.stringify(user);
}
}
function clientCode(middleware: Middleware) {
const payload = {username: "[email protected]", password: "123456"};
console.log(`Logging..`);
const result = middleware.handle(payload.username, payload.password);
console.log(`${result}`);
}
const checkValidMiddleware = new CheckValidPayload();
const checkEmailExitsMiddleware = new CheckEmailExits();
const loginMiddleware = new Login();
checkValidMiddleware.setNext(checkEmailExitsMiddleware).setNext(loginMiddleware);
clientCode(checkValidMiddleware);