summaryrefslogtreecommitdiff
path: root/pbt/ts/src/levelbank.ts
blob: 298e8ad788034598856cedcbbf987cbe38235d90 (plain)
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
// Specify types of keys and values (any, in the case of json).

import {Level} from 'level';
import {Account, Bank} from './bank.js';
import {Option, fromNullable} from 'fp-ts/lib/Option.js';

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);
    }
  }
}