Skip to main content

Realtime Updates

This tutorial is about using Macrometa GDN as a realtime database with local latencies across the globe.

Pre-requisite

Let's assume your

Driver download

With Yarn or NPM

yarn add jsc8
(or)
npm install jsc8

If you want to use the driver outside of the current directory, you can also install it globally using the `--global` flag:

npm install --global jsc8

From source,

git clone https://github.com/macrometacorp/jsc8.git
cd jsC8
npm install
npm run dist

Code Sample

const jsc8 = require('jsc8');

// Variables - DB
const global_url = "https://gdn.paas.macrometa.io";

// Crete a authenticated instance with Token / Apikey
// const client = new jsc8({url: global_url, token: "XXXX", fabricName: '_system'});
// const client = new jsc8({url: global_url, apiKey: "XXXX", fabricName: '_system'});
// await console.log("Authentication done!!...");

// Or use Email & Password to Authenticate client instance
const client = new jsc8(global_url);

await client.login("[email protected]", "xxxxxx");

//Variables
const collection_name = "ddos";
let collectionDetails;

// Variables - Data
const data = [
{"ip": "10.1.1.1", "action": "block", "rule": "blacklistA"},
{"ip": "20.1.1.2", "action": "block", "rule": "blacklistA"},
{"ip": "30.1.1.3", "action": "block", "rule": "blacklistB"},
{"ip": "40.1.1.4", "action": "block", "rule": "blacklistA"},
{"ip": "50.1.1.5", "action": "block", "rule": "blacklistB"},
];

async function createCollection() {
console.log("\n 2. CREATE_COLLECTION");

try{
console.log(`Creating the collection ${collection_name}...`);
const exists_coll = await client.hasCollection(collection_name);
if (exists_coll === false) {
await client.createCollection(collection_name);
}

// adding a onChange listner for collection
const listener = await client.onCollectionChange(collection_name);
listener.on('message',(msg) => console.log("message=>", msg));
listener.on('open',() => {
this.callback_fn(collection);
});
listener.on('close',() => console.log("connection closed"));
}
catch (e) {
await console.log("Collection creation did not succeed due to " + e);
}
}

async function insertData() {
console.log(`\n 3. INSERT_DATA in region ${global_url}`);
await client.insertDocumentMany(collection_name, data);
}

async function deleteData(){
console.log("\n 4. DELETE_DATA");
await client.deleteCollection(collection_name);
}

(async function(){
await createCollection();
await insertData();
await deleteData();
})();