Queries as API

This tutorial is about using C8QL queries in Macrometa GDN as API with local latencies across the globe.

Pre-requisite

Let's assume your

  • Tenant name is guest@macrometa.io and
  • User password is guest.

Driver download


pyC8 requires Python 3.5+. Python 3.6 or higher is recommended

To install pyC8, simply run

    $ pip3 install pyC8

or, if you prefer to use conda:

    conda install -c conda-forge pyC8

or pipenv:

    pipenv install --pre pyC8

Once the installation process is finished, you can begin developing applications in Python.

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

from c8 import C8Client
import pprint

# Variables - URLs
global_url = "gdn1.macrometa.io"

# Variables - DB
email = "guest@macrometa.io"
password = "guest"
geo_fabric = "_system"
collection_name = "address"

# Variables - RESTQLs
parameter = {"firstname": "", "lastname": "", "email": "", "zipcode": ""}
insert_data = {
    "query": {
        "name": "insertRecord",
        "value": "INSERT {'firstname':@firstname, 'lastname':@lastname, 'email':@email, 'zipcode':@zipcode, '_key': 'abc'} IN %s" % collection_name,
        "parameter": parameter
    }
}
get_data = {
    "query": {
        "name": "getRecords",
        "value": "FOR doc IN %s RETURN doc" % collection_name
    }
}
update_data = {
    "query": {
        "name": "updateRecord",
        "value": "UPDATE 'abc' WITH { \"lastname\": \"cena\" } IN %s" % collection_name
    }
}
delete_data = {
    "query": {
        "name": "deleteRecord",
        "value": "REMOVE 'abc' IN %s" % collection_name
    }
}
get_count = {
    "query": {
        "name": "countRecords",
        "value": "RETURN COUNT(FOR doc IN %s RETURN 1)" % collection_name
    }
}

pp = pprint.PrettyPrinter(indent=4)

if __name__ == '__main__':

  # Step1: Open connection to GDN. You will be routed to closest region.
  print("1. CONNECT: federation: {},  user: {}".format(global_url, email))
  client = C8Client(protocol='https', host=global_url, port=443)
  tenant = client.tenant(email, password)
  fabric = tenant.useFabric(geo_fabric)

  # Step2: Create a collection if not exists
  print("2. CREATE_COLLECTION: region: {},  collection: {}".format(global_url, collection_name))
  if fabric.has_collection(collection_name):
      collection = fabric.collection(collection_name)
  else:
      collection = fabric.create_collection(collection_name)

  # Step3: Create RestQLs
  print("3. CREATE_RESTQLs: region: {}".format(global_url))
  fabric.save_restql(insert_data)  # name: insertRecord
  fabric.save_restql(get_data)  # name: getRecords
  fabric.save_restql(update_data)  # name: updateRecord
  fabric.save_restql(delete_data)  # name: deleteRecord
  fabric.save_restql(get_count)  # name: countRecords
  pp.pprint(fabric.get_all_restql())

  # Step4: Execute RestQLs
  print("4. EXECUTE_RESTQLs: region: {}".format(global_url))

  print("\t a. Insert data....")
  response = fabric.execute_restql(
      "insertRecord", {
          "bindVars": {
              "firstname": "john",
              "lastname": "doe",
              "email": "john.doe@macrometa.io",
              "zipcode": "511037"
          }
      })
  print("\t b. Get data....")
  response = fabric.execute_restql("getRecords")
  pp.pprint(response['result'])
  print("\t c. Update data....")
  response = fabric.execute_restql("updateRecord")
  print("\t d. Get data....")
  response = fabric.execute_restql("getRecords")
  pp.pprint(response['result'])
  print("\t e. Count records....")
  response = fabric.execute_restql("countRecords")
  pp.pprint(response['result'])
  print("\t f. Delete data....")
  response = fabric.execute_restql("deleteRecord")

  print("5. DELETE_RESTQLs: region: {}".format(global_url))
  fabric.delete_restql("insertRecord")
  fabric.delete_restql("getRecords")
  fabric.delete_restql("updateRecord")
  fabric.delete_restql("countRecords")
  fabric.delete_restql("deleteRecord")
'use strict'

const jsc8 = require('jsc8')

// Variables - DB
const global_url = "https://gdn1.macrometa.io"
const client = new jsc8(global_url)
const guest_password = "guest"
const geo_fabric = "_system"
const guest_email = "guest@macrometa.io"
const collection_name = "address"
let collection_address = null


// Variables - RESTQLs
let parameter = {"firstname": "", "lastname": "", "email": "", "zipcode": ""}

let insert_data = {
    "query": {
        "name": "insertRecord",
        "value": `INSERT {'firstname':@firstname, 'lastname':@lastname, 'email':@email, 'zipcode':@zipcode, '_key': 'abc'} IN ${collection_name}`,
        "parameter": parameter

    }
}

let get_data = {
    "query": {
        "name": "getRecords",
        "value": `FOR doc IN ${collection_name} RETURN doc` 
    }
}

let update_data = {
    "query": {
        "name": "updateRecord",
        "value": `UPDATE 'abc' WITH { \"lastname\": \"cena\" } IN ${collection_name}`
    }
}

let delete_data = {
    "query": {
        "name": "deleteRecord",
        "value": `REMOVE 'abc' IN ${collection_name}` 
    }
}

let get_count = {
    "query": {
        "name": "countRecords",
        "value": `RETURN COUNT(FOR doc IN ${collection_name} RETURN 1)`
    }
}

async function login(){
  console.log(`\n 1. CONNECT: federation: ${global_url}`);
  await client.login(guest_email, guest_password);
  await client.useFabric(geo_fabric);
}

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

  try{
      collection_address = client.collection(collection_name)
      let exists_coll = await collection_address.exists()
      if (exists_coll === false) {
            await collection_address.create()

        }

      }
    catch (e) {
    await console.log("Collection creation did not succeed due to " + e)
    }
}

async function createRestQL(){
  console.log("\n 3. CREATE_RESTQLS")
  await client.saveQuery(insert_data.query.name.toString(), insert_data.query.parameter, insert_data.query.value.toString());

  await client.saveQuery(get_data.query.name.toString(), {}, get_data.query.value.toString())

  await client.saveQuery(update_data.query.name.toString(), {}, update_data.query.value.toString())

  await client.saveQuery(delete_data.query.name.toString(), {}, delete_data.query.value.toString())

  await client.saveQuery(get_count.query.name.toString(), {}, get_count.query.value.toString())
}


async function executeRestQL(){
  console.log("\n 4. EXECUTE_RESTQLS")
  console.log("\n a. Insert Data")
  let resp = await client.executeSavedQuery(insert_data.query.name.toString(),        {"firstname": "john","lastname": "doe","email": "john.doe@macrometa.io","zipcode": "511037"});
  console.log(resp.result)

  console.log("\n b. Get Data")
  resp = await client.executeSavedQuery(get_data.query.name.toString(), {});
  console.log(resp.result)

  console.log("\n c. Update Data")
  resp = await client.executeSavedQuery(update_data.query.name.toString(), {})
  console.log(resp.result)

  console.log("\n d. Get Data")
  resp = await client.executeSavedQuery(get_data.query.name.toString(), {});
  console.log(resp.result)

  console.log("\n e. Count Records")
  resp = await client.executeSavedQuery(get_count.query.name.toString(), {})
  console.log(resp.result)

  console.log("\n f. Delete Record")
  resp = await client.executeSavedQuery(delete_data.query.name.toString(), {})
  console.log(resp.result)
}

async function deleteRestQL(){
   console.log("\n 4. DELETE_RESTQLS")
  await client.deleteSavedQuery(insert_data.query.name.toString());
  await client.deleteSavedQuery(get_data.query.name.toString());
  await client.deleteSavedQuery(update_data.query.name.toString())
  await client.deleteSavedQuery(get_data.query.name.toString());
  await client.deleteSavedQuery(get_count.query.name.toString())
  await client.deleteSavedQuery(delete_data.query.name.toString())

}


(async function(){
  await login();
  await createCollection();
  await createRestQL();
  await executeRestQL();
  await deleteRestQL();

})();
Top