JavaScript
We’re overhauling Dgraph’s docs to make them clearer and more approachable. If you notice any issues during this transition or have suggestions, please let us know.
The official Dgraph client implementation for JavaScript, using gRPC-js (the original gRPC client for JavaScript is now deprecated).
This client follows the Dgraph Go client closely.
You can find the official Dgraph JavaScript gRPC client at: https://github.com/hypermodeinc/dgraph-js. Follow the installation instructions to get it up and running.
Supported versions
More details on the supported versions can be found at this link.
Quickstart
Build and run the simple project, which contains an end-to-end example of using the Dgraph JavaScript client. Follow the instructions in the README of that project.
Examples
- Simple: Quickstart example of using dgraph-js.
- TLS: Example of using dgraph-js with a Dgraph cluster secured with TLS.
Using a client
You can find a simple example project, which contains an end-to-end working example of how to use the JavaScript gRPC client, for Node.js >= v6.
Creating a client
A DgraphClient
object can be initialized by passing it a list of
DgraphClientStub
clients as arguments. Connecting to multiple Dgraph servers
in the same cluster allows for better distribution of workload.
The following code snippet shows just one connection.
To facilitate debugging, debug mode can be enabled for a client.
Multi-tenancy
In multi-tenancy environments, dgraph-js
provides a new method loginIntoNamespace()
, which allows the users to login to
a specific namespace.
In order to create a JavaScript client, and make the client login into namespace
123
:
In this example, the client logs into namespace 123
using username groot
and
password password
. Once logged in, the client can perform all the operations
allowed to the groot
user of namespace 123
.
Altering the database
To set the schema, create an Operation
object, set the schema and pass it to
DgraphClient#alter(Operation)
method.
Starting Dgraph version 20.03.0, indexes can be computed in the background. You
can set setRunInBackground
field of the Operation
object to true
before
passing it to the DgraphClient#alter(Operation)
method. You can find more
details here.
NOTE: Many of the examples here use the
await
keyword which requiresasync/await
support which is available on Node.js >= v7.6.0. For prior versions, the expressions followingawait
can be used just like normalPromise
:
Operation
contains other fields as well, including drop predicate and drop
all. Drop all is useful if you wish to discard all the data, and start from a
clean slate, without bringing the instance down.
Creating a transaction
To create a transaction, call DgraphClient#newTxn()
method, which returns a
new Txn
object. This operation incurs no network overhead.
It is good practice to call Txn#discard()
in a finally
block after running
the transaction. Calling Txn#discard()
after Txn#commit()
is a no-op and you
can call Txn#discard()
multiple times with no additional side-effects.
To create a read-only transaction, set readOnly
boolean to true
while
calling DgraphClient#newTxn()
method. Read-only transactions can’t contain
mutations and trying to call Txn#mutate()
or Txn#commit()
results in an
error. Calling Txn.Discard()
is a no-op.
You can optionally set the bestEffort
boolean to true
. This may yield
improved latencies in read-bound workloads where the guaranteed latest value is
not strictly needed.
Running a mutation
Txn#mutate(Mutation)
runs a mutation. It takes in a Mutation
object, which
provides two main ways to set data, JSON and RDF N-Quad. You can choose
whichever way is convenient.
We define a person object to represent a person and use it in a Mutation
object.
For a more complete example with multiple fields and relationships, look at the
[simple] project in the examples
folder.
Sometimes, you only want to commit a mutation, without querying anything
further. In such cases, you can use Mutation#setCommitNow(true)
to indicate
that the mutation must be immediately committed.
Mutation#setIgnoreIndexConflict(true)
can be applied on a Mutation
object to
not run conflict detection over the index, which would decrease the number of
transaction conflicts and aborts. However, this would come at the cost of
potentially inconsistent upsert operations.
Mutation can be run using txn.doRequest
as well.
Running a query
You can run a query by calling Txn#query(string)
. You need to pass in a DQL
query string. If you want to pass an additional map of any variables that you
might want to set in the query, call Txn#queryWithVars(string, object)
with
the variables object as the second argument.
The response would contain the method Response#getJSON()
, which returns the
response JSON.
Let’s run the following query with a variable $a:
Run the query, deserialize the result from Uint8Array (or base64) encoded JSON and print it out:
This should print:
You can also use txn.doRequest
function to run the query.
Running an upsert: query + mutation
The txn.doRequest
function allows you to run upserts consisting of one query
and one mutation. Query variables could be defined and can then be used in the
mutation. You can also use the txn.doRequest
function to perform just a query
or a mutation.
Running a conditional upsert
The upsert block allows specifying a conditional mutation block using an @if
directive. The mutation is executed only when the specified condition is true.
If the condition is false, the mutation is silently ignored.
See more about Conditional Upsert Here.
Committing a transaction
A transaction can be committed using the Txn#commit()
method. If your
transaction consisted solely of calls to Txn#query
or Txn#queryWithVars
, and
no calls to Txn#mutate
, then calling Txn#commit()
isn’t necessary.
An error is returned if other transactions running concurrently modify the same data that was modified in this transaction. It is up to the user to retry transactions when they fail.
Clean up resources
To clean up resources, you have to call DgraphClientStub#close()
individually
for all the instances of DgraphClientStub
.
Debug mode
Debug mode can be used to print helpful debug messages while performing alters,
queries, and mutations. It can be set using
theDgraphClient#setDebugMode(boolean?)
method.
Setting metadata headers
Metadata headers such as authentication tokens can be set through the context of
gRPC methods. Below is an example of how to set a header named auth-token
.
Was this page helpful?