summaryrefslogtreecommitdiff
path: root/pbt/ts/src/levelbank.ts
diff options
context:
space:
mode:
Diffstat (limited to 'pbt/ts/src/levelbank.ts')
-rw-r--r--pbt/ts/src/levelbank.ts52
1 files changed, 52 insertions, 0 deletions
diff --git a/pbt/ts/src/levelbank.ts b/pbt/ts/src/levelbank.ts
new file mode 100644
index 0000000..ead4e38
--- /dev/null
+++ b/pbt/ts/src/levelbank.ts
@@ -0,0 +1,52 @@
+// Specify types of keys and values (any, in the case of json).
+
+import {Level} from 'level';
+import {Account, Bank} from './bank';
+import {Option, fromNullable} from 'fp-ts/lib/Option';
+
+export class LevelBank implements Bank {
+ db: Level<string, number>;
+ file: string;
+
+ constructor(file: string) {
+ this.file = file;
+ this.db = new Level<Account, number>(file, {
+ valueEncoding: 'json',
+ });
+ }
+
+ async populateWith(
+ initialAccounts: Map<Account, number>,
+ ): Promise<LevelBank> {
+ await this.db.open({createIfMissing: true});
+
+ const puts: Promise<void>[] = [];
+
+ initialAccounts.forEach((v, k) => {
+ puts.push(this.db.put(k, v));
+ });
+
+ await Promise.all(puts);
+
+ return this;
+ }
+
+ async balance(account: string): Promise<Option<number>> {
+ const result = await this.db.get(account);
+ return fromNullable(result);
+ }
+
+ async deposit(account: string, amt: number): Promise<void> {
+ const current = await this.db.get(account);
+ if (current) {
+ await this.db.put(account, current + amt);
+ }
+ }
+
+ async withdraw(account: string, amt: number): Promise<void> {
+ const current = await this.db.get(account);
+ if (current) {
+ await this.db.put(account, current + amt);
+ }
+ }
+}