-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaccount.js
More file actions
115 lines (90 loc) · 2.55 KB
/
account.js
File metadata and controls
115 lines (90 loc) · 2.55 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class Account {
constructor ({ code, name, currency = '', parent }, adapter) {
if (!code) {
throw new Error('Undefined code');
}
this.code = code;
this.name = name || code;
this.currency = currency;
this.parent = parent;
this._attach(adapter);
}
get attached () {
return Boolean(this.adapter);
}
/**
* Add child account
* @param {Account} account
* @param {object} options
*/
async addChild (account, options) {
if (!this.attached) {
throw new Error('Detached from adapter');
}
if (account instanceof Account === false) {
throw new Error('Account to add is not an account');
}
if (account.parent) {
throw new Error('Account to add is a child of other account');
}
account._attach(this.adapter);
await account.setParent(this, options);
}
async removeChild (account, options) {
if (!this.attached) {
throw new Error('Detached from adapter');
}
if (account instanceof Account === false) {
throw new Error('Child is not an account');
}
if (account.parent !== this.code) {
throw new Error('Account to remove is not a child of account');
}
await account.removeParent(options);
}
getParent (options) {
if (!this.parent || !this.attached) {
return;
}
return this.adapter._get(this.parent, options);
}
async getChild (code, options) {
if (!this.attached) {
throw new Error('Detached from adapter');
}
let rawAccount = await this.adapter._get(code, options);
if (!rawAccount || rawAccount.parent !== this.code) {
return;
}
return new Account(rawAccount, this.adapter);
}
async getChildren (options) {
if (!this.attached) {
throw new Error('Detached from adapter');
}
let rawAccounts = await this.adapter._findByParent(this.code, options);
return rawAccounts.map(a => new Account(a, this.adapter));
}
getEntries (criteria, options) {
criteria = Object.assign({}, criteria, { code: this.code });
return this.adapter._entries(criteria, options);
}
getBalance (options) {
return this.adapter._balance(this.code, options);
}
async setParent (parent, options) {
this.parent = parent.code;
await this.adapter._connect(this, options);
}
async removeParent (options) {
await this.adapter._disconnect(this, options);
this.parent = undefined;
}
_attach (adapter) {
Object.defineProperty(this, 'adapter', {
configurable: true,
get: () => adapter,
});
}
}
module.exports = { Account };