-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-Repository.ts
More file actions
41 lines (30 loc) · 892 Bytes
/
1-Repository.ts
File metadata and controls
41 lines (30 loc) · 892 Bytes
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
// Entity DAO
type RawUser = { id: number; name: string };
class UserDAO {
constructor(public options: { fake: true }) {}
getById(id: number): Promise<RawUser> {
if (!this.options.fake) throw new Error('Not a fake');
return Promise.resolve({ id, name: 'Marcus Aurelius' });
}
}
// Domain Entity
class User {
constructor(public id: number, public name: string) {}
}
// Repository
class UserRepository {
constructor(private dao: UserDAO) {}
async findById(id: number): Promise<User> {
const raw = await this.dao.getById(id);
if (!raw) throw new Error(`Record not found: User(${id})`);
return new User(raw.id, raw.name);
}
}
// Usage
const main = async () => {
const userDAO = new UserDAO({ fake: true });
const userRepositoty = new UserRepository(userDAO);
const user = await userRepositoty.findById(1011);
console.log({ user });
};
main();