-
Notifications
You must be signed in to change notification settings - Fork 0
/
Base.ts
92 lines (72 loc) · 1.97 KB
/
Base.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 { Constructor } from 'web-utility';
import { observable, action } from 'mobx';
import * as MobX from 'mobx';
import {
IDType,
DataObject,
NewData,
InvalidMessage,
RESTClient,
toggle
} from './utility';
export abstract class BaseModel {
constructor() {
MobX.makeObservable?.(this);
}
@observable
downloading = 0;
@observable
uploading = 0;
@action
clear() {
this.downloading = this.uploading = 0;
}
}
/**
* This basic class is a middle class, which isn't for direct using
*/
export abstract class BaseListModel<D extends DataObject> extends BaseModel {
constructor() {
super();
MobX.makeObservable?.(this);
}
abstract client: RESTClient;
abstract baseURI: string;
indexKey: keyof D = 'id';
@observable
currentOne = {} as D;
@observable
validity: InvalidMessage<D> = {};
static createNested(parentId: IDType) {
const Model = this as unknown as Constructor<BaseListModel<{}>>;
const store = new Model();
store.baseURI = store.baseURI.replace(/:\w+/, parentId + '');
return store;
}
@action
clearCurrent() {
this.currentOne = {} as D;
this.validity = {};
}
clear() {
super.clear();
this.clearCurrent();
}
@toggle('uploading')
async updateOne(data: Partial<NewData<D>>, id?: IDType) {
const { body } = await (id
? this.client.patch<D>(`${this.baseURI}/${id}`, data)
: this.client.post<D>(this.baseURI, data));
return (this.currentOne = body);
}
@toggle('downloading')
async getOne(id: IDType) {
const { body } = await this.client.get<D>(`${this.baseURI}/${id}`);
return (this.currentOne = body);
}
@toggle('uploading')
async deleteOne(id: IDType) {
await this.client.delete(`${this.baseURI}/${id}`);
if (this.currentOne[this.indexKey] === id) this.clearCurrent();
}
}