-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSRP.ts
66 lines (53 loc) · 1.59 KB
/
SRP.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
const myDB = {
users: [],
} as { users: User[] };
// Single Responsibility Principle
// The User class has only one responsibility: storing information about the user.
// Would it be a kind of Model??
class User {
id: number;
name: string;
constructor(name: string) {
this.id = Math.random();
this.name = name;
}
getName() {
return this.name;
}
}
// The UserRepository class is responsible for communicating with the database to save and retrieve information about users.
class UserRepository {
// If I use the User class as a Parameter, create a dependency??
// The correct thing would be to create an Interface??
save(user: User) {
myDB.users.push(user);
}
get(id: number) {
// Retrieve user from database
return myDB.users.find((user) => user.id === id);
}
}
// The UserService class is responsible for managing user save and recovery operations.
class UserService {
private userRepository: UserRepository;
constructor(userRepository: UserRepository) {
this.userRepository = userRepository;
}
saveUser(user: User) {
const exists = this.getUser(user.id);
if (exists) throw new Error("User already exists");
return this.userRepository.save(user);
}
getUser(id: number) {
return this.userRepository.get(id);
}
}
//Factorys
const user = new User("John Doe"); // Models
const userRepository = new UserRepository(); // Repository || ORM
const userService = new UserService(userRepository); // Service
//Controllers
// Dependency Injection
userService.saveUser(user);
const savedUser = userService.getUser(user.id);
console.log(savedUser);