Skip to main content

Realtime DB Updates Example

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

Prerequisites

  • A Macrometa account with sufficient permissions to create streams.
  • An API key. For more information, refer to Create API Keys.
  • Appropriate SDK installed. For more information, refer to Install SDKs.

Realtime Updates Code

const jsc8 = require("jsc8");

// Constants - DB
const globalUrl = "https://play.paas.macrometa.io/";
const email = "your@email.com";
const password = "password";
const client = new jsc8(globalUrl);

// Variables
const collectionName = "ddos";
let listener;
const data = [
{ ip: "10.1.1.1", action: "block", rule: "blocklistA" },
{ ip: "20.1.1.2", action: "block", rule: "blocklistA" },
{ ip: "30.1.1.3", action: "block", rule: "blocklistB" },
{ ip: "40.1.1.4", action: "block", rule: "blocklistA" },
{ ip: "50.1.1.5", action: "block", rule: "blocklistB" }
];

const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
};

// Create an authenticated instance with a token or API key

// const client = new jsc8({url: globalUrl, token: "XXXX", fabricName: '_system'});
// const client = new jsc8({url: globalUrl, apiKey: "XXXX", fabricName: '_system'});

// Or use email and password to authenticate client instance

async function createCollection () {
console.log("\n1. Log in.");
await client.login(email, password);
console.log("\n2. Create collection.");
try {
console.log(`Creating the collection ${collectionName}...`);
const existsColl = await client.hasCollection(collectionName);
if (existsColl === false) {
await client.createCollection(collectionName, { stream: true });
}
// Add an onChange listener for collection
listener = await client.onCollectionChange(collectionName);

// Decode the message printed here in readable format
listener.on("message", (msg) => {
const receivedMsg = msg && JSON.parse(msg);
console.log("message=>", Buffer.from(receivedMsg.payload, "base64").toString("ascii"))
});
listener.on("open", () => console.log("Connection open"));
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(`\n3. Insert data in region ${globalUrl}`);
await client.insertDocumentMany(collectionName, data);
}
async function deleteData () {
console.log("\n4. Delete data");
await client.deleteCollection(collectionName);
}
(async function () {
await createCollection();
await sleep(2000);
await insertData();
await sleep(10000);
await listener.close();
await deleteData();
})();