-
Notifications
You must be signed in to change notification settings - Fork 6
/
EntityStore.ts
92 lines (75 loc) · 1.96 KB
/
EntityStore.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
81
82
83
84
85
86
87
88
89
90
91
92
import { makeAutoObservable } from 'mobx';
import { Repository, Identifier } from './Repository';
// TODO: implement generic type for the entity
export class EntityStore {
loading = false;
data: unknown | null = null;
identifier: Identifier | null = null;
constructor(private repository: Repository) {
makeAutoObservable<EntityStore, 'repository'>(
this,
{ repository: false },
{ autoBind: true }
);
}
setLoading(loading: boolean) {
this.loading = loading;
}
setData(data: unknown | null) {
this.data = data;
}
setIdentifier(identifier: Identifier) {
this.identifier = identifier;
}
async fetch() {
if (!this.identifier) {
return console.warn("Can't fetch without an identifier");
}
this.setLoading(true);
try {
const response = await this.repository.read(this.identifier);
this.setData(response.data);
this.setLoading(false);
} catch (error) {
this.setLoading(false);
throw error;
}
}
// TODO: Implement update with different methods: patch and put
async update(data: object) {
if (!this.identifier) {
return console.warn("Can't update without an identifier");
}
this.setLoading(true);
try {
const response = await this.repository.patch(this.identifier, data);
if (this.data) {
this.setData({ ...this.data, ...response.data });
}
this.setLoading(false);
return response.data;
} catch (error) {
this.setLoading(false);
throw error;
}
}
async delete() {
if (!this.identifier) {
return console.warn("Can't delete without an identifier");
}
this.setLoading(true);
try {
await this.repository.delete(this.identifier);
this.setData(null);
this.setLoading(false);
} catch (error) {
this.setLoading(false);
throw error;
}
}
reset() {
this.identifier = null;
this.data = null;
this.loading = false;
}
}