Giter VIP home page Giter VIP logo

dgraph-js-http's Introduction

dgraph-js-http

npm version Coverage Status

A Dgraph client implementation for javascript using HTTP. It supports both browser and Node.js environments.

Looking for gRPC support? Check out dgraph-js.

This client follows the Dgraph Javascript gRPC 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 yarn:

yarn add dgraph-js-http

or npm:

npm install dgraph-js-http

You will also need a Promise polyfill for older browsers and Node.js v5 and below. We recommend taylorhakes/promise-polyfill for its small size and Promises/A+ compatibility.

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-http version
21.3.X 21.3.0
22.0.X 21.3.0
23.0.X 23.0.0

Quickstart

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

Using a client

Create 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-http");

const clientStub = new dgraph.DgraphClientStub(
    // addr: optional, default: "http://localhost:8080"
    "http://localhost:8080",
    // legacyApi: optional, default: false. Set to true when connecting to Dgraph v1.0.x
    false,
);
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-http 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:

await dgraphClient.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.

If you're connecting to Dgraph Cloud, call setCloudApiKey before calling loginIntoNamespace.

Create 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-http");

//here we pass the cloud endpoint
const clientStub = new dgraph.DgraphClientStub(
    "https://super-pail.us-west-2.aws.cloud.dgraph.io",
);

const dgraphClient = new dgraph.DgraphClient(clientStub);

//here we pass the API key
dgraphClient.setCloudApiKey("<api-key>");

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

Login into Dgraph

If your Dgraph server has Access Control Lists enabled (Dgraph v1.1 or above), the clientStub must be logged in for accessing data:

await clientStub.login("groot", "password");

Calling login will obtain and remember the access and refresh JWT tokens. All subsequent operations via the logged in clientStub will send along the stored access token.

Access tokens expire after 6 hours, so in long-lived apps (e.g. business logic servers) you need to login again on a periodic basis:

// When no parameters are specified the clientStub uses existing refresh token
// to obtain a new access token.
await clientStub.login();

Configure access tokens

Some Dgraph configurations require extra access tokens.

  1. Alpha servers can be configured with Secure Alter Operations. In this case the token needs to be set on the client instance:
dgraphClient.setAlphaAuthToken("My secret token value");
  1. Dgraph Cloud requires API key for HTTP access:
dgraphClient.setCloudApiKey("Copy the Api Key from Dgraph Cloud admin page");

Create https connection

If your cluster is using tls/mtls you can pass a node https.Agent configured with you certificates as follows:

const https = require("https");
const fs = require("fs");
// read your certificates
const cert = fs.readFileSync("./certs/client.crt", "utf8");
const ca = fs.readFileSync("./certs/ca.crt", "utf8");
const key = fs.readFileSync("./certs/client.key", "utf8");

// create your https.Agent
const agent = https.Agent({
    cert,
    ca,
    key,
});

const clientStub = new dgraph.DgraphClientStub(
    "https://localhost:8080",
    false,
    { agent },
);
const dgraphClient = new dgraph.DgraphClient(clientStub);

Alter the database

To set the schema, pass the schema to DgraphClient#alter(Operation) method.

const schema = "name: string @index(exact) .";
await dgraphClient.alter({ schema: schema });

NOTE: Many of the examples here use the await keyword which requires async/await support which is not available in all javascript environments. For unsupported environments, the expressions following await can be used just like normal Promise instances.

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.
await dgraphClient.alter({ dropAll: true });

Create 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();
    // ...
}

You can make queries read-only and best effort by passing options to DgraphClient#newTxn. For example:

const options = { readOnly: true, bestEffort: true };
const res = await dgraphClient.newTxn(options).query(query);

Read-only transactions are useful to increase read speed because they can circumvent the usual consensus protocol. Best effort queries can also increase read speed in read bound system. Please note that best effort requires readonly.

Run 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.
await txn.mutate({ setJson: p });

For a more complete example with multiple fields and relationships, look at the simple project in the examples folder.

For setting values using N-Quads, use the setNquads field. For delete mutations, use the deleteJson and deleteNquads fields for deletion using JSON and N-Quads respectively.

Sometimes, you only want to commit a mutation, without querying anything further. In such cases, you can use Mutation#commitNow = true to indicate that the mutation must be immediately committed.

// Run mutation.
await txn.mutate({ setJson: p, commitNow: true });

Run 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 data field, Response#data, 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 and print out the response:

// 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.data;

// 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

Commit 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();
}

Check request latency

To see the server latency information for requests, check the extensions.server_latency field from the Response object for queries or from the Assigned object for mutations. These latencies show the amount of time the Dgraph server took to process the entire request. It does not consider the time over the network for the request to reach back to the client.

// queries
const res = await txn.queryWithVars(query, vars);
console.log(res.extensions.server_latency);
// { parsing_ns: 29478,
//  processing_ns: 44540975,
//  encoding_ns: 868178 }

// mutations
const assigned = await txn.mutate({ setJson: p });
console.log(assigned.extensions.server_latency);
// { parsing_ns: 132207,
//   processing_ns: 84100996 }

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);

Development

Building the source

npm run build

Running tests

The script run-tests.sh spins up a local cluster and runs the npm tests.

bash scripts/run-tests.sh

dgraph-js-http's People

Contributors

aelbannan avatar arjuninv avatar bucanero avatar danielmai avatar dependabot[bot] avatar gja avatar gpahal avatar janbehrens avatar joshua-goldstein avatar manishrjain avatar mbj36 avatar micheldiz avatar prashant-shahi avatar ryanfoxtyler avatar sleto-it avatar sydney-o9 avatar vardhanapoorv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dgraph-js-http's Issues

Remove LinRead from code.

As LinRead ins't been used by Dgraph anymore and is causing issues with CORS. Need to be cleanup.

Vue component

Similar to it would be fantastic to have a component that could run queries and mutations in the same fashion, but with a much cleaning code.

How hard would it be to wrap this "dgraph-js-http"?

Browser example : How to bundle the 'dgraph-js-http' lib in an HTML page

http1.zip

There is an example for Node.js on server side that is working well.
https://github.com/dgraph-io/dgraph-js-http/tree/master/examples/simple

Now when you want to test it on the browser side the require directive is not reconised by the JS on the browser side. " const dgraph = require("dgraph-js-http"); " gives an error.

I manage to use a "bundler " and got to the next series of problems ;)
Could you please provide with an example ?

This worked a little :
browserify index-promise.js > bundle.js

[Deps] Find new TS linter

Running npm install on current package gives unresolved peer dependency:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/tslint
npm ERR!   dev tslint@"^6.1.3" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer tslint@"^5.1.0" from [email protected]
npm ERR! node_modules/tslint-microsoft-contrib
npm ERR!   dev tslint-microsoft-contrib@"^6.2.0" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/tslint
npm ERR!   peer tslint@"^5.1.0" from [email protected]
npm ERR!   node_modules/tslint-microsoft-contrib
npm ERR!     dev tslint-microsoft-contrib@"^6.2.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Hence why we currently require npm install --legacy-peer-deps. This is because https://github.com/microsoft/tslint-microsoft-contrib is out of date and no longer maintained. We should switch to a more modern linter. Perhaps https://github.com/typescript-eslint/typescript-eslint.

Problems using dgraph-js-http and dgraph-js with VUE

When importing dgraph-js or dgraph-js-http into VUE JS, I get errors.

Environment:

  • npm 6.3.0
  • vue-cli 3.0.0-rc.11

To replicate do the following:

vue create dgraph_project

  • select manually (babel, router, vuex)
    -- the other choices are not that relevant.

cd dgraph_project
yarn add dgraph-js-http grpc dgraph-js

Add the following to the src/main.js file

import dgraph from 'dgraph-js'

yarn serve

Goto http://localhost:8080/ and check the console log in the browser.

Errors

For dgraph-js

TypeError: process.version is undefined

For dgraph-js-http

[Vue warn]: Error in render: "TypeError: dgraph_js_http__WEBPACK_IMPORTED_MODULE_0___default.a is undefined"
When I try to invoke the library by running the simple example.

I suspect that the use webpack 4 might be the reason for this problem.
However, I would appreciate if the dgraph-js library could work "out of the box" with vue-cli v3 and webpack 4.

Sorry for the trouble.

dgraph-ratel

From Installed Binary

dgraph-ratel -version

Ratel Version:

localhost:8000
errot:We seem to have difficulties loading latest client. Try using the pac

ERR_NO_CLIENTS with a DgraphClientStub provided

I'm trying to use the module in an Electron application but I get the ERR_NO_CLIENTS: Error: No clients provided in DgraphClient constructor error. The DgraphClientStub however is provided and alpha / zero are both running and reachable through ratel.

const dgraph = require('dgraph-js-http')

const dgraphClientStub = new dgraph.DgraphClientStub()
const dgraphClient = new dgraph.DgraphClient(dgraphClientStub)

console.log(dgraph, dgraphClient, dgraphClientStub)

I've tried with the latest version "dgraph-js-http": "20.3.0"

screenshot-20200427114604907598485

and branch v1.1.0-rc2 "dgraph-js-http": "file:/./build-steps/dgraph-js-http-1.1.0-rc2".

screenshot-20200427190011298738225

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.