Integrating the Graph API with Node.js

Cosmos DB supports graph using gremlin support, and gremlin is supported in Node.js for a long time.

We can install the gremlin node modules using the following command:

npm install gremlin@latest
Always lock the dependencies in production.

You can create a new Graph API in Azure portal and copy the connection details. I am going to show the sample code to connect to that graph database.

We have installed the node module. Let's place our configuration details in one file:

var config = {}
    
config.endpoint = "graph api end point";
config.primaryKey = "primary key";
config.database = "database name"
config.collection = "collection name"
    
module.exports = config;

Now, we can connect to the Graph DB using the following code:

var Gremlin = require('gremlin');
var config = require("./config");
    
var client = Gremlin.createClient(
    443, 
    config.endpoint, 
    { 
        "session": false, 
        "ssl": true, 
        "user": `/dbs/${config.database}/colls/${config.collection}`,
        "password": config.primaryKey
    }
);

You can run the code using node <filename.js> and if the connection string is bad, it will throw an error and exit.

You can use execute(query) function to perform the queries in your graph database, for example:

This code piece will return the number of vertices present in the graph:

client.execute("g.V().count()", { }, (err, results) => {
  if (err) return console.error(err);
  console.log("Result: %sn", JSON.stringify(results));
});

Similarly, you can execute other queries as well.

This covers the Node.js integration with Graph DB as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.79.241