Author of this content has low reputation.

Dhive to MongoDB Typescript Example

I've been a DevOps engineer my whole career and I decided to try programming on Hive as it is great motivation to support a blockchain I'm invested in, like contributing writing to, and helping others build reputation on the internet for Hive. All that makes it fun.

So it's quite easy to program in Typescript/Express/Node and it took me only 2 days to refresh myself to be able to submit block IDs to a MongoDB database.

I hope this code helps anyone who is curious for developing apps on Hive. This was my first attempt at executing an Obituary frontend and CUSTOM_JSON interface which seems to be quite feasible with dhive.

I recommend the following post by @gtg for exploring what would work best for your app. The dhive library is fantastic. Their docs are linked below:

@gtg/a-curated-list-of-awesome-hive-resources

https://openhive-network.github.io/dhive/

Here is a working example of submitting every block to a MongoDB database. I am a novice, so any critiques would be great.

import { Client } from "@hiveio/dhive";
const client = new Client(["https://api.pharesim.me", "https://api.hivekings.com", "https://anyx.io", "https://api.openhive.network"]);



// Use connect method to connect to the server
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
 
// Connection URL
const url = 'mongodb://27017';
 
// Database Name
const dbName = 'hive';
 

async function getHiveBlocks() {
  for await (const block of client.blockchain.getBlocks()) {
    return "id:" + `${block.block_id}`;
  }
}



function MongoConnection(){
  MongoClient.connect(url, function(err, MongoBomb) {
    assert.equal(null, err);
    console.log("Connected successfully to server");
   
    const db = MongoBomb.db(dbName);
  
  
  
  
 function findDocuments(db){
    // Get the documents collection
    const collection = db.collection('blocks');
    // Find some documents
    collection.find({}).toArray(function(err, docs) {
      assert.equal(err, null);
      console.log("Found the following records");
      console.log(docs)
      MongoBomb.close();
    });
  }
  
  
function insertHiveBlocks(db) {
    console.log("test");
    // Get the documents collection
    const collection = db.collection('blocks');
    // Insert some document
    collection.insertOne(getHiveBlocks()), function(err, result) {
      try{ 
        console.log("MADE IT")
        assert.equal(err, null);
        assert.equal(1, result.result.n);
        assert.equal(1, result.ops.length);
        console.log("Inserted 1 documents into the collection");
        MongoBomb.close();
      } catch {
        console.log("POOP");
      }
    }
  }


insertHiveBlocks(db);
findDocuments(db);
MongoBomb.close();
  })
}
MongoConnection();
H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center