Skip to content
Muhammad Yasir edited this page Oct 18, 2022 · 10 revisions

ENAPSO Graph Database Client for Node.js

Node.js client for Ontotext GraphDB, Stardog, and Apache Jena Fuseki to easily perform SPARQL queries and update statements against your RDF stores, your OWL ontologies, or knowledge graphs in Node.js applications.

Use Cases

Authenticate the user against the graph database

Authenticate against Graph Database using JWT:

graphDBEndpoint.login('admin','root').then((result) => {
        console.log(result);
    })
    .catch((err) => {
        console.log(err);
    });

If the connection cannot be established, e.g. because the database is not available at the given URL, you'll get an HTTP 500 error message:

{
    "success": false,
    "message": "Error: connect ECONNREFUSED 127.0.0.1:7201",
    "statusCode": 500
}

In case of invalid credentials or insufficient access rights, you'll get an HTTP 401 error message:

{
    "success": false,
    "message": "401 - Bad credentials",
    "statusCode": 401
}

Querying Graph Database

Execute a SPARQL query against the database and transform the bindings to an easily processible JSON resultset:

graphDBEndpoint
    .query(
        'select *
where {
    ?class rdf:type owl:Class
    filter(regex(str(?class), "http://ont.enapso.com/test#TestClass", "i")) .
}',
        { transform: 'toJSON' }
    )
    .then((result) => {
        console.log(
            'Read the classes name:\n' + JSON.stringify(result, null, 2)
        );
    })
    .catch((err) => {
        console.log(err);
    });

If you want to convert the query result result to a format other than the globally defined one, you can see the above explicit example. In case a matching record is found, the result looks like this:

{
    "total": 1,
    "success": true,
    "records": [
        {
            "class": "http://ont.enapso.com/test#TestClass"
        }
    ]
}

In case of errors in the query, you'll get an HTTP 400 error message:

{
    "statusCode": 400,
    "message": "HTTP Error: 400 Bad Request",
    "success": false
}

In case of insufficient access rights, you'll get an HTTP 403 error message:

{
    "statusCode": 403,
    "message": "HTTP Error: 403 Forbidden",
    "success": false
}

Inserting Triples in Graph Database

This is how can you can insert triples into your graph:

graphDBEndpoint
    .update(
        `insert data {
		graph <http://ont.enapso.com/test> {
      entest:TestClass rdf:type owl:Class}
  }`
    )
    .then((result) => {
        console.log('inserted a class :\n' + JSON.stringify(result, null, 2));
    })
    .catch((err) => {
        `console.log(err);
    });

If the insert operation was successful, you'll get the following result:

{
    "success": true,
    "statusCode": 200,
    "message": "OK"
}

Updating Triples in graph database

This is how you can update triples in your graph:

graphDBEndpoint
    .update(
        `with <http://ont.enapso.com/test>
		delete {
		  entest:TestClass rdf:type owl:Class
		}
		insert {
		  entest:TestClassUpdated rdf:type owl:Class
		}
		where {
		  entest:TestClass rdf:type owl:Class
		}`
    )
    .then((result) => {
        console.log(
            'Updated the inserted class name:\n' +
                JSON.stringify(result, null, 2)
        );
    })
    .catch((err) => {
        console.log(err);
    });

In case the update operation was successful, you'll get the following result:

{
    "success": true,
    "statusCode": 200,
    "message": "OK"
}

Delete Triples in graph database

This is how you can delete triples in your graph:

graphDBEndpoint
    .update(
        `with <http://ont.enapso.com/test>
		delete {
			entest:TestClassUpdated rdf:type owl:Class
		}
		where {
			entest:TestClassUpdated rdf:type owl:Class
		}`
    )
    .then((result) => {
        console.log('Delete the class:\n' + JSON.stringify(result, null, 2));
    })
    .catch((err) => {
        console.log(err);
    });

In case the update operation was successful, you'll get the following result:

{
    "success": true,
    "statusCode": 200,
    "message": "OK"
}

Standard SPARQL JSON binding

In case of a successful query, a SPARQL-compliant JSON is returned. For this low-level call, the result neither contains a status code nor a message. In addition to the success flag, you can interpret the existence of the head, results, and bindings fields as success criteria.

{
    "head": {
        "vars": ["iri", "firstName", "lastName"]
    },
    "results": {
        "bindings": [
            {
                "iri": {
                    "type": "uri",
                    "value": "http://ont.enapso.com/test#Person_AlexanderSchulze"
                },
                "firstName": {
                    "type": "literal",
                    "value": "Alexander"
                },
                "lastName": {
                    "type": "literal",
                    "value": "Schulze"
                }
            },
            {
                "iri": {
                    "type": "uri",
                    "value": "http://ont.enapso.com/test#Person_JohnDoe"
                },
                "firstName": {
                    "type": "literal",
                    "value": "John"
                },
                "lastName": {
                    "type": "literal",
                    "value": "Doe"
                }
            }
        ]
    },
    "success": true
}

Beautified ENAPSO JSON Resultset

{
    "total": 2,
    "success": true,
    "records": [
        {
            "iri": "entest:Person_AlexanderSchulze",
            "firstName": "Alexander",
            "lastName": "Schulze"
        },
        {
            "iri": "entest:Person_JohnDoe",
            "firstName": "John",
            "lastName": "Doe"
        }
    ]
}

Error Handling

In case the login fails due to the unavailability of the database, the following error will be returned:

{
    "success": false,
    "code": "ECONNREFUSED",
    "message": "Error: connect ECONNREFUSED 127.0.0.1:7200",
    "statusCode": 500
}

In case of invalid credentials, the following error will be returned:

{
    "success": false,
    "message": "401 - Bad credentials",
    "statusCode": 401
}

In case of errors during the execution of the query, the following error will be returned:

{
    "success": false,
    "statusCode": 400,
    "message": "HTTP Error: 400 Bad Request"
}

CSV and TSV Results

The ENAPSO Graph Database Client enables you to easily export query results to CSV and TSV files.

csv = this.graphDBEndpoint.transformBindingsToCSV(query);

returns the following object:

{
    "total": 2,
    "success": true,
    "headers": ["iri,firstName,lastName"],
    "records": [
        "http://ont.enapso.com/test#Person_AlexanderSchulze,Alexander,Schulze",
        "http://ont.enapso.com/test#Person_JohnDoe,John,Doe"
    ]
}

that easily can be written to a file e.g. by the following code:

fs.writeFileSync(
    'examples/examples.csv',
    // optionally add headers
    csv.headers.join('\r\n') +
        '\r\n' +
        // add the csv records to the file
        csv.records.join('\r\n')
);

In case you require more detailed control over the separator and/or string delimiter characters you can use:

csv = this.graphDBEndpoint.transformBindingsToSeparatedValues(query, {
    // replace IRIs by prefixes for easier
    // resultset readability (optional)
    replacePrefixes: true,
    // drop the prefixes for easier
    // resultset readability (optional)
    // "dropPrefixes": true,
    separator: ',',
    separatorEscape: '\\,',
    delimiter: '"',
    delimiterEscape: '\\"'
});

Formats

Most of the databases support the import and export of graphs in numerous formats. The ENAPSO Graph Database Client provides the available formats as constants. You can use them in your application, for instance, by EnapsoGraphDBClient.FORMAT_TURTLE.

"FORMAT_JSON": {
  "name": "JSON",
  "type": "application/rdf+json",
  "extension": ".json"
},
"FORMAT_JSON_LD": {
  "name": "JSON-LD",
  "type": "application/ld+json",
  "extension": ".jsonld"
},
"FORMAT_RDF_XML": {
  "name": "RDF-XML",
  "type": "application/rdf+xml",
  "extension": ".rdf"
},
"FORMAT_N3": {
  "name": "N3",
  "type": "text/rdf+n3",
  "extension": ".n3"
},
"FORMAT_N_TRIPLES": {
  "name": "N-Triples",
  "type": "text/plain",
  "extension": ".nt"
},
"FORMAT_N_QUADS": {
  "name": "N-Quads",
  "type": "text/x-nquads",
  "extension": ".nq"
},
"FORMAT_TURTLE": {
  "name": "Turtle",
  "type": "text/turtle",
  "extension": ".ttl"
},
"FORMAT_TRIX": {
  "name": "TriX",
  "type": "application/trix",
  "extension": ".trix"
},
"FORMAT_TRIG": {
  "name": "TriG",
  "type": "application/x-trig",
  "extension": ".trig"
},
"FORMAT_BINARY_RDF": {
  "name": "Binary RDF",
  "type": "application/x-binary-rdf",
  "extension": ".brf"
}

Prefixes

The following prefixes are already predefined in the ENAPSO Graph Database Client:

"PREFIX_OWL": {
  "prefix": "owl",
  "iri": "http://www.w3.org/2002/07/owl#"
},
"PREFIX_RDF": {
  "prefix": "rdf",
  "iri": "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
},
"PREFIX_RDFS": {
  "prefix": "rdfs",
  "iri": "http://www.w3.org/2000/01/rdf-schema#"
},
"PREFIX_XSD": {
  "prefix": "xsd",
  "iri": "http://www.w3.org/2001/XMLSchema#"
},
"PREFIX_FN": {
  "prefix": "fn",
  "iri": "http://www.w3.org/2005/xpath-functions#"
},
"PREFIX_SFN": {
  "prefix": "sfn",
  "iri": "http://www.w3.org/ns/sparql#"
}
"PREFIX_ONTOFN": {
  "prefix": "ontofn",
  "iri": "http://www.ontotext.com/sparql/functions/#"
},
"PREFIX_SPIF": {
  "prefix": "spif",
  "iri": "http://spinrdf.org/spif#"
},
"PREFIX_APROPF": {
  "prefix": "aprof",
  "iri": "http://jena.hpl.hp.com/ARQ/property#"
},
"PREFIX_ALIST": {
  "prefix": "alist",
  "iri": "http://jena.apache.org/ARQ/list#"
}