• Stars
    star
    322
  • Rank 130,398 (Top 3 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created almost 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Official Dgraph JavaScript client

dgraph-js npm version Build Status Coverage Status

Official Dgraph client implementation for JavaScript (Node.js v6 and above), using gRPC.

Use Discuss Issues for reporting issues about this repository.

Looking for browser support? Check out dgraph-js-http.

This client follows the Dgraph Go client closely.

Before using this client, we highly recommend that you go through docs.dgraph.io, and understand how to run and work with Dgraph.

Table of contents

Install

Install using npm:

npm install dgraph-js grpc --save
# If you are using Typescript, you might also need:
# npm install @types/google-protobuf @types/protobufjs --save-dev

or yarn:

yarn add dgraph-js grpc
# If you are using Typescript, you might also need:
# yarn add @types/google-protobuf @types/protobufjs --dev

Supported Versions

Depending on the version of Dgraph that you are connecting to, you will have to use a different version of this client.

Dgraph version dgraph-js version
1.0.X 1.X.Y
1.1.X 2.X.Y
20.03.0 20.03.0
21.03.0 21.03.0

Note: Only API breakage from v1.X.Y to v2.X.Y is in the function DgraphClient.newTxn().mutate(). This function returns a messages.Assigned type in v1.X but a messages.Response type in v2.X.

Quickstart

Build and run the simple project in the examples folder, which contains an end-to-end example of using the Dgraph JavaScript client. Follow the instructions in the README of that project.

Using a Client

Creating a Client

A DgraphClient object can be initialised by passing it a list of DgraphClientStub clients as variadic arguments. Connecting to multiple Dgraph servers in the same cluster allows for better distribution of workload.

The following code snippet shows just one connection.

const dgraph = require("dgraph-js");
const grpc = require("grpc");

const clientStub = new dgraph.DgraphClientStub(
  // addr: optional, default: "localhost:9080"
  "localhost:9080",
  // credentials: optional, default: grpc.credentials.createInsecure()
  grpc.credentials.createInsecure(),
);
const dgraphClient = new dgraph.DgraphClient(clientStub);

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 will allow the users to login to a specific namespace.

In order to create a JavaScript client, and make the client login into namespace 123:

const dgraphClientStub = new dgraph.DgraphClientStub("localhost:9080");
await dgraphClientStub.loginIntoNamespace("groot", "password", 123); // where 123 is the namespaceId 

In the example above, 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.

Creating a Client for Dgraph Cloud Endpoint

If you want to connect to Dgraph running on your Dgraph Cloud instance, then all you need is the URL of your Dgraph Cloud endpoint and the API key. You can get a client using them as follows:

const dgraph = require("dgraph-js");

const clientStub = dgraph.clientStubFromCloudEndpoint(
  "https://frozen-mango.eu-central-1.aws.cloud.dgraph.io/graphql",
  "<api-key>"
);
const dgraphClient = new dgraph.DgraphClient(clientStub);

Note: the clientStubFromSlashGraphQLEndpoint method is deprecated and will be removed in the next release. Instead use clientStubFromCloudEndpoint method.

Altering the Database

To set the schema, create an Operation object, set the schema and pass it to DgraphClient#alter(Operation) method.

const schema = "name: string @index(exact) .";
const op = new dgraph.Operation();
op.setSchema(schema);
await dgraphClient.alter(op);

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.

const schema = "name: string @index(exact) .";
const op = new dgraph.Operation();
op.setSchema(schema);
op.setRunInBackground(true);
await dgraphClient.alter(op);

NOTE: Many of the examples here use the await keyword which requires async/await support which is available on Node.js >= v7.6.0. For prior versions, the expressions following await can be used just like normal Promise:

dgraphClient.alter(op)
    .then(function(result) { ... }, function(err) { ... })

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.

// Drop all data including schema from the Dgraph instance. This is useful
// for small examples such as this, since it puts Dgraph into a clean
// state.
const op = new dgraph.Operation();
op.setDropAll(true);
await dgraphClient.alter(op);

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 practise 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.

const txn = dgraphClient.newTxn();
try {
  // Do something here
  // ...
} finally {
  await txn.discard();
  // ...
}

To create a read-only transaction, set readOnly boolean to true while calling DgraphClient#newTxn() method. Read-only transactions cannot contain mutations and trying to call Txn#mutate() or Txn#commit() will result in an error. Calling Txn.Discard() will be a no-op.

You can optionally set the bestEffort boolean to true. This may yield improved latencies in read-bound workloads where linearizable reads are not strictly needed.

const txn = dgraphClient.newTxn({
  readOnly: true,
  bestEffort: false
});
// ...
const res = await txn.queryWithVars(query, vars);

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.

// Create data.
const p = {
    name: "Alice",
};

// Run mutation.
const mu = new dgraph.Mutation();
mu.setSetJson(p);
await txn.mutate(mu);

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.

const mu = new dgraph.Mutation();
mu.setSetJson(p);

const req = new dgraph.Request();
req.setCommitNow(true);
req.setMutationsList([mu]);

await txn.doRequest(req);

Running a Query

You can run a query by calling Txn#query(string). You will need to pass in a GraphQL+- 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:

query all($a: string) {
  all(func: eq(name, $a))
  {
    name
  }
}

Run the query, deserialize the result from Uint8Array (or base64) encoded JSON and print it out:

// Run query.
const query = `query all($a: string) {
  all(func: eq(name, $a))
  {
    name
  }
}`;
const vars = { $a: "Alice" };
const res = await dgraphClient.newTxn().queryWithVars(query, vars);
const ppl = res.getJson();

// Print results.
console.log(`Number of people named "Alice": ${ppl.all.length}`);
ppl.all.forEach((person) => console.log(person.name));

This should print:

Number of people named "Alice": 1
Alice

You can also use txn.doRequest function to run the query.

const req = new dgraph.Request();
const vars = req.getVarsMap();
vars.set("$a", "Alice");
req.setQuery(query);

const res = await txn.doRequest(req);
console.log(JSON.stringify(res.getJson()));

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.

To know more about upsert, we highly recommend going through the docs at https://docs.dgraph.io/mutations/#upsert-block.

const query = `
  query {
      user as var(func: eq(email, "[email protected]"))
  }`

const mu = new dgraph.Mutation();
mu.setSetNquads(`uid(user) <email> "[email protected]" .`);

const req = new dgraph.Request();
req.setQuery(query);
req.setMutationsList([mu]);
req.setCommitNow(true);

// Upsert: If wrong_email found, update the existing data
// or else perform a new mutation.
await dgraphClient.newTxn().doRequest(req);

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.

const query = `
  query {
      user as var(func: eq(email, "[email protected]"))
  }`

const mu = new dgraph.Mutation();
mu.setSetNquads(`uid(user) <email> "[email protected]" .`);
mu.setCond(`@if(eq(len(user), 1))`);

const req = new dgraph.Request();
req.setQuery(query);
req.addMutations(mu);
req.setCommitNow(true);

await dgraphClient.newTxn().doRequest(req);

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() is not necessary.

An error will be 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.

const txn = dgraphClient.newTxn();
try {
  // ...
  // Perform any number of queries and mutations
  // ...
  // and finally...
  await txn.commit();
} catch (e) {
  if (e === dgraph.ERR_ABORTED) {
    // Retry or handle exception.
  } else {
    throw e;
  }
} finally {
  // Clean up. Calling this after txn.commit() is a no-op
  // and hence safe.
  await txn.discard();
}

Cleanup Resources

To cleanup resources, you have to call DgraphClientStub#close() individually for all the instances of DgraphClientStub.

const SERVER_ADDR = "localhost:9080";
const SERVER_CREDENTIALS = grpc.credentials.createInsecure();

// Create instances of DgraphClientStub.
const stub1 = new dgraph.DgraphClientStub(SERVER_ADDR, SERVER_CREDENTIALS);
const stub2 = new dgraph.DgraphClientStub(SERVER_ADDR, SERVER_CREDENTIALS);

// Create an instance of DgraphClient.
const dgraphClient = new dgraph.DgraphClient(stub1, stub2);

// ...
// Use dgraphClient
// ...

// Cleanup resources by closing all client stubs.
stub1.close();
stub2.close();

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.

// Create a client.
const dgraphClient = new dgraph.DgraphClient(...);

// Enable debug mode.
dgraphClient.setDebugMode(true);
// OR simply dgraphClient.setDebugMode();

// Disable debug mode.
dgraphClient.setDebugMode(false);

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".

// The following piece of code shows how one can set metadata with
// auth-token, to allow Alter operation, if the server requires it.

var meta = new grpc.Metadata();
meta.add('auth-token', 'mySuperSecret');

await dgraphClient.alter(op, meta);

Examples

  • simple: Quickstart example of using dgraph-js.
  • tls: Example of using dgraph-js with a Dgraph cluster secured with TLS.

Development

Building the source

npm run build

If you have made changes to the proto/api.proto file, you need need to regenerate the source files generated by Protocol Buffer tools. To do that, install the Protocol Buffer Compiler and then run the following command:

npm run build:protos

Running tests

Make sure you have a Dgraph server running on localhost before you run this task.

npm test

More Repositories

1

dgraph

The high-performance database for modern applications
Go
19,791
star
2

badger

Fast key-value DB in Go.
Go
12,961
star
3

ristretto

A high performance memory-bound Go cache
Go
5,088
star
4

dgo

Official Dgraph Go client
Go
347
star
5

sroar

Serialized Roaring Bitmaps
Go
267
star
6

pydgraph

Official Dgraph Python client
Python
261
star
7

dgraph4j

Official Dgraph Java client
Java
157
star
8

travel

Starter Kit For Building Graph Database Go and Browser Apps Using Dgraph
Go
126
star
9

graphoverflow

Run the entire StackOverflow on Dgraph. Work in progress.
JavaScript
116
star
10

ratel

Dgraph Data Visualizer and Cluster Manager
JavaScript
114
star
11

wisemonk

Bot to move conversations from Slack to Discourse.
Go
106
star
12

benchmarks

Run benchmarks with RDF data
Go
97
star
13

badger-bench

Benchmarks of Badger
Go
92
star
14

graphql-sample-apps

This repository contains sample GraphQL applications powered by Dgraph.
JavaScript
73
star
15

dgraph-js-http

A JavaScript HTTP client for Dgraph
TypeScript
67
star
16

gru

Help identify the right minions
JavaScript
46
star
17

dgraph-lambda

TypeScript
39
star
18

tutorial

A Tour of Dgraph
HTML
38
star
19

dgraph-docs

A native GraphQL Database with a graph backend
Shell
35
star
20

charts

Helm charts for Dgraph
Shell
32
star
21

ingressutil

Utils for building an ingress controller
Go
31
star
22

flock

Twitter on Dgraph
Go
31
star
23

dgraph.net

Official Dgraph .NET Client
C#
28
star
24

dgraph-operator

Dgraph Operator creates/configures/manages Dgraph clusters atop Kubernetes
Go
23
star
25

hugo-dgraph-theme

Hugo theme used for our blog
CSS
22
star
26

typhoon-ui

🌀 typhoon-ui: Token-based React component library built using emotion.
TypeScript
14
star
27

hugo-docs

Theme for Dgraph documentation built via Hugo
HTML
13
star
28

experiments

Go
13
star
29

graphql-kanban

Project management app written with Dgraph and Apollo Client
TypeScript
13
star
30

mediawiki-dgraph-skin

Mediawiki skin used by Dgraph wiki.
CSS
13
star
31

svelte-urql-example

Svelte
12
star
32

slash-graphql-cli

Command Line Tools for Slash GraphQL
TypeScript
11
star
33

auth-webinar

Resources for Serverless Authentication + Authorization Webinar
JavaScript
9
star
34

discuss-tutorial

Discuss clone app built for a tutorial
CSS
8
star
35

tove

Crash vulnerability tests for Badger using the ALICE framework
Go
7
star
36

graphql-dgraph-web

GraphQL Web
SCSS
7
star
37

graphql-asia-workshop-2020

JavaScript
7
star
38

rails-graphoverflow

Showcase of using Dgraph in Ruby on Rails
Ruby
7
star
39

dgraph-react-todomvc

TodoMVC in React with GraphQL, Dgraph, NoSQL graph database
JavaScript
7
star
40

grpc-proxy

Go
6
star
41

webinar-1-twitter-graphql

JavaScript
5
star
42

react-slash-graphql-starter

JavaScript
4
star
43

gatsby-dgraph-graphql

A simple blog app with Gatsby and Dgraph's GraphQL API
JavaScript
4
star
44

auth0-integration

Slash GraphQL + Auth0 integration quick start
JavaScript
4
star
45

tweetsletter-workshop

JavaScript
4
star
46

dgraph-day

Learn graph database best practices from experts using Dgraph at scale in production and building the next generation of apps. Sign up for the FREE virtual event, April 15-16th.
4
star
47

hello

Dgraph's take on Go present
JavaScript
3
star
48

live-demo

JavaScript
3
star
49

dev-jokes

Slash powered DevJokes Application
JavaScript
3
star
50

Install-Dgraph

Dgraph installation scripts
Shell
2
star
51

workshop

Dgraph workshop: Build a Twitter graph with Dgraph!
2
star
52

video-tutorial-todo

JavaScript
2
star
53

vlg

Dgraph's Very Large Graph (WIP) Project
Go
2
star
54

website-old

Website code for dgraph.io
CSS
2
star
55

tudo-tutorial

Tutorial for building a GraphQL React app with Slash GraphQL
JavaScript
2
star
56

dgraph-io.github.io

Dgraph blog
HTML
2
star
57

cloud-docs

Documentation for Dgraph Cloud
Shell
1
star
58

discuss-tutorial-vue

CSS
1
star
59

developer-connect-sessions

1
star