simple-db.ts 1.69 KB
Newer Older
smartcontracts's avatar
smartcontracts committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Imports: External */
import { LevelUp } from 'levelup'
import { BigNumber } from 'ethers'

export class SimpleDB {
  constructor(public db: LevelUp) {}

  public async get<TEntry>(key: string, index: number): Promise<TEntry | null> {
    try {
      // TODO: Better checks here.
      return JSON.parse(await this.db.get(this._makeKey(key, index)))
    } catch (err) {
      return null
    }
  }

  public async range<TEntry>(
    key: string,
    startIndex: number,
    endIndex: number
  ): Promise<TEntry[] | []> {
    try {
23
      return new Promise<any[]>((resolve) => {
smartcontracts's avatar
smartcontracts committed
24 25 26 27 28 29 30 31 32
        const entries: any[] = []
        this.db
          .createValueStream({
            gte: this._makeKey(key, startIndex),
            lt: this._makeKey(key, endIndex),
          })
          .on('data', (transaction: string) => {
            entries.push(JSON.parse(transaction))
          })
33
          .on('error', () => {
smartcontracts's avatar
smartcontracts committed
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
            resolve(null)
          })
          .on('close', () => {
            // TODO: Close vs end? Need to double check later.
            resolve(entries)
          })
          .on('end', () => {
            resolve(entries)
          })
      })
    } catch (err) {
      return []
    }
  }

  public async put<TEntry>(
    entries: {
      key: string
      index: number
      value: TEntry
    }[]
  ): Promise<void> {
    return this.db.batch(
      entries.map((entry) => {
        return {
          type: 'put',
          key: this._makeKey(entry.key, entry.index),
          value: JSON.stringify(entry.value),
        }
      })
    )
  }

  private _makeKey(key: string, index: number): string {
68
    // prettier-ignore
smartcontracts's avatar
smartcontracts committed
69 70 71
    return `${key}:${BigNumber.from(index).toString().padStart(32, '0')}`
  }
}