# All files / src/api createDb.js

100% Statements 27/27
100% Branches 4/4
100% Functions 11/11
100% Lines 24/24

    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
    821x

    7x
    2x

    7x
    1x
    1x
    1x

    1x

    1x

    1x

    1x
    1x

    7x
    4x

    2x

    1x

    2x
    1x

    7x
    1x

    7x
    3x

    7x

    1x
     const createDb = levelDb => {
      /*
      * Returns last synced block number from the db. If there is no such a number, returns 0
      */
      const getLastBlockSynced = () =>
        levelDb.get('lastBlockSynced').catch(maybeNotFound => 0); // eslint-disable-line no-unused-vars

      /*
    * Stores block and all it's txs into level db.
    * Sets lastBlockSynced value to the given block height.
    */
      const storeBlock = async block => {
        const dbOpsBatch = levelDb.batch();
        block.txList.forEach((tx, txPos) => {
          dbOpsBatch.put(
            `tx!${tx.hash()}`,
            JSON.stringify({
              txData: tx.toJSON(),
              blockHash: block.hash(),
              height: block.height,
              txPos,
            })
          );
        });

        dbOpsBatch.put(
          `block!${block.hash()}`,
          JSON.stringify({
            blockData: block.toJSON(),
            height: block.height,
          })
        );

        // index blocks by height for getBlockByNumber
        dbOpsBatch.put(`block!${block.height}`, block.hash());

        dbOpsBatch.put('lastBlockSynced', block.height);

        return new Promise(resolve => {
          dbOpsBatch.write(resolve);
        });
      };

      const getNullable = key => {
        return levelDb
          .get(key)
          .then(jsonStr => {
            // hash, not object
            if (jsonStr.indexOf('0x') === 0) return jsonStr;

            return JSON.parse(jsonStr);
          })
          .catch(e => {
            if (e.type === 'NotFoundError') return null;
            throw e;
          });
      };

      /*
    * Returns block data for given hash
    */
      const getBlock = hash => {
        return getNullable(`block!${hash}`);
      };

      /*
    * Returns tx data for given hash
    */
      const getTransaction = hash => {
        return getNullable(`tx!${hash}`);
      };

      return {
        getLastBlockSynced,
        storeBlock,
        getBlock,
        getTransaction,
      };
    };

    module.exports = createDb;