{"id":20613947,"url":"https://github.com/dgraph-io/dgraph-js-http","last_synced_at":"2025-04-13T00:45:43.960Z","repository":{"id":38271720,"uuid":"135894657","full_name":"dgraph-io/dgraph-js-http","owner":"dgraph-io","description":"A JavaScript HTTP client for Dgraph","archived":false,"fork":false,"pushed_at":"2025-02-04T12:48:40.000Z","size":985,"stargazers_count":69,"open_issues_count":0,"forks_count":21,"subscribers_count":24,"default_branch":"main","last_synced_at":"2025-04-13T00:45:38.744Z","etag":null,"topics":["client","dgraph","http","javascript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dgraph-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-06-03T10:32:19.000Z","updated_at":"2025-02-04T12:48:44.000Z","dependencies_parsed_at":"2024-06-26T14:05:29.331Z","dependency_job_id":"ddab168c-e40a-4fe5-b72f-97f9156cac64","html_url":"https://github.com/dgraph-io/dgraph-js-http","commit_stats":{"total_commits":124,"total_committers":17,"mean_commits":7.294117647058823,"dds":0.6370967741935484,"last_synced_commit":"b55b17934072a3e2b23e7a201aa1f64f944bbb88"},"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fdgraph-js-http","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fdgraph-js-http/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fdgraph-js-http/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fdgraph-js-http/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dgraph-io","download_url":"https://codeload.github.com/dgraph-io/dgraph-js-http/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248650420,"owners_count":21139672,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client","dgraph","http","javascript"],"created_at":"2024-11-16T11:11:28.940Z","updated_at":"2025-04-13T00:45:43.937Z","avatar_url":"https://github.com/dgraph-io.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# dgraph-js-http \n[![npm version](https://img.shields.io/npm/v/dgraph-js-http.svg?style=flat)](https://www.npmjs.com/package/dgraph-js-http) [![Coverage Status](https://img.shields.io/coveralls/github/dgraph-io/dgraph-js-http/master.svg?style=flat)](https://coveralls.io/github/dgraph-io/dgraph-js-http?branch=master)\n\nA Dgraph client implementation for javascript using HTTP. It supports both\nbrowser and Node.js environments.\n\n**Looking for gRPC support? Check out [dgraph-js][grpcclient].**\n\nThis client follows the [Dgraph Javascript gRPC client][grpcclient] closely.\n\n[grpcclient]: https://github.com/dgraph-io/dgraph-js\n\nBefore using this client, we highly recommend that you go through [docs.dgraph.io],\nand understand how to run and work with Dgraph.\n\n[docs.dgraph.io]: https://docs.dgraph.io\n\n## Table of contents\n\n-   [Install](#install)\n-   [Supported Versions](#supported-versions)\n-   [Quickstart](#quickstart)\n-   [Using a client](#using-a-client)\n    -   [Create a client](#create-a-client)\n    -   [Login into Dgraph](#login-into-dgraph)\n    -   [Configure access tokens](#configure-access-tokens)\n    -   [Alter the database](#alter-the-database)\n    -   [Create a transaction](#create-a-transaction)\n    -   [Run a mutation](#run-a-mutation)\n    -   [Run a query](#run-a-query)\n    -   [Commit a transaction](#commit-a-transaction)\n    -   [Check request latency](#check-request-latency)\n    -   [Debug mode](#debug-mode)\n-   [Development](#development)\n    -   [Building the source](#building-the-source)\n    -   [Running tests](#running-tests)\n\n## Install\n\nInstall using `yarn`:\n\n```sh\nyarn add dgraph-js-http\n```\n\nor npm:\n\n```sh\nnpm install dgraph-js-http\n```\n\nYou will also need a Promise polyfill for\n[older browsers](http://caniuse.com/#feat=promises) and Node.js v5 and below.\nWe recommend [taylorhakes/promise-polyfill](https://github.com/taylorhakes/promise-polyfill)\nfor its small size and Promises/A+ compatibility.\n\n## Supported Versions\n\nDepending on the version of Dgraph that you are connecting to, you will have to\nuse a different version of this client.\n\n| Dgraph version | dgraph-js-http version |\n| :------------: | :--------------------: |\n|    21.3.X      |       *21.3.0*         |\n|    22.0.X      |       *21.3.0*         |\n|    23.0.X      |       *23.0.0*         |\n\n## Quickstart\n\nBuild and run the [simple] project in the `examples` folder, which\ncontains an end-to-end example of using the Dgraph javascript HTTP client. Follow\nthe instructions in the README of that project.\n\n[simple]: https://github.com/dgraph-io/dgraph-js-http/tree/master/examples/simple\n\n## Using a client\n\n### Create a client\n\nA `DgraphClient` object can be initialised by passing it a list of\n`DgraphClientStub` clients as variadic arguments. Connecting to multiple Dgraph\nservers in the same cluster allows for better distribution of workload.\n\nThe following code snippet shows just one connection.\n\n```js\nconst dgraph = require(\"dgraph-js-http\");\n\nconst clientStub = new dgraph.DgraphClientStub(\n    // addr: optional, default: \"http://localhost:8080\"\n    \"http://localhost:8080\",\n    // legacyApi: optional, default: false. Set to true when connecting to Dgraph v1.0.x\n    false,\n);\nconst dgraphClient = new dgraph.DgraphClient(clientStub);\n```\n\nTo facilitate debugging, [debug mode](#debug-mode) can be enabled for a client.\n\n### Multi-tenancy\n\nIn [multi-tenancy](https://dgraph.io/docs/enterprise-features/multitenancy) environments, `dgraph-js-http` provides a new method `loginIntoNamespace()`,\nwhich will allow the users to login to a specific namespace.\n\nIn order to create a JavaScript client, and make the client login into namespace `123`:\n\n```js\nawait dgraphClient.loginIntoNamespace(\"groot\", \"password\", 123); // where 123 is the namespaceId \n```\n\nIn the example above, the client logs into namespace `123` using username `groot` and password `password`.\nOnce logged in, the client can perform all the operations allowed to the `groot` user of namespace `123`.\n\nIf you're connecting to Dgraph Cloud, call `setCloudApiKey` before calling `loginIntoNamespace`.\n\n### Create a Client for Dgraph Cloud Endpoint\n\nIf you want to connect to Dgraph running on your [Dgraph Cloud](https://cloud.dgraph.io) 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:\n\n```js\nconst dgraph = require(\"dgraph-js-http\");\n\n//here we pass the cloud endpoint\nconst clientStub = new dgraph.DgraphClientStub(\n    \"https://super-pail.us-west-2.aws.cloud.dgraph.io\",\n);\n\nconst dgraphClient = new dgraph.DgraphClient(clientStub);\n\n//here we pass the API key\ndgraphClient.setCloudApiKey(\"\u003capi-key\u003e\");\n```\n\n**Note:** the `setSlashApiKey` method is deprecated and will be removed in the next release. Instead use `setCloudApiKey` method.\n\n### Login into Dgraph\n\nIf your Dgraph server has Access Control Lists enabled (Dgraph v1.1 or above),\nthe clientStub must be logged in for accessing data:\n\n```js\nawait clientStub.login(\"groot\", \"password\");\n```\n\nCalling `login` will obtain and remember the access and refresh JWT tokens.\nAll subsequent operations via the logged in `clientStub` will send along the\nstored access token.\n\nAccess tokens expire after 6 hours, so in long-lived apps (e.g. business logic servers)\nyou need to `login` again on a periodic basis:\n\n```js\n// When no parameters are specified the clientStub uses existing refresh token\n// to obtain a new access token.\nawait clientStub.login();\n```\n\n### Configure access tokens\n\nSome Dgraph configurations require extra access tokens.\n\n1. Alpha servers can be configured with [Secure Alter Operations](https://dgraph.io/docs/deploy/dgraph-administration/#securing-alter-operations).\n   In this case the token needs to be set on the client instance:\n\n```js\ndgraphClient.setAlphaAuthToken(\"My secret token value\");\n```\n\n2. [Dgraph Cloud](https://cloud.dgraph.io) requires API key for HTTP access:\n\n```js\ndgraphClient.setCloudApiKey(\"Copy the Api Key from Dgraph Cloud admin page\");\n```\n\n### Create https connection\n\nIf your cluster is using tls/mtls you can pass a node `https.Agent` configured with you\ncertificates as follows:\n\n```js\nconst https = require(\"https\");\nconst fs = require(\"fs\");\n// read your certificates\nconst cert = fs.readFileSync(\"./certs/client.crt\", \"utf8\");\nconst ca = fs.readFileSync(\"./certs/ca.crt\", \"utf8\");\nconst key = fs.readFileSync(\"./certs/client.key\", \"utf8\");\n\n// create your https.Agent\nconst agent = https.Agent({\n    cert,\n    ca,\n    key,\n});\n\nconst clientStub = new dgraph.DgraphClientStub(\n    \"https://localhost:8080\",\n    false,\n    { agent },\n);\nconst dgraphClient = new dgraph.DgraphClient(clientStub);\n```\n\n### Alter the database\n\nTo set the schema, pass the schema to `DgraphClient#alter(Operation)` method.\n\n```js\nconst schema = \"name: string @index(exact) .\";\nawait dgraphClient.alter({ schema: schema });\n```\n\n\u003e NOTE: Many of the examples here use the `await` keyword which requires\n\u003e `async/await` support which is not available in all javascript environments.\n\u003e For unsupported environments, the expressions following `await` can be used\n\u003e just like normal `Promise` instances.\n\n`Operation` contains other fields as well, including drop predicate and drop all.\nDrop all is useful if you wish to discard all the data, and start from a clean\nslate, without bringing the instance down.\n\n```js\n// Drop all data including schema from the Dgraph instance. This is useful\n// for small examples such as this, since it puts Dgraph into a clean\n// state.\nawait dgraphClient.alter({ dropAll: true });\n```\n\n### Create a transaction\n\nTo create a transaction, call `DgraphClient#newTxn()` method, which returns a\nnew `Txn` object. This operation incurs no network overhead.\n\nIt is good practise to call `Txn#discard()` in a `finally` block after running\nthe transaction. Calling `Txn#discard()` after `Txn#commit()` is a no-op\nand you can call `Txn#discard()` multiple times with no additional side-effects.\n\n```js\nconst txn = dgraphClient.newTxn();\ntry {\n    // Do something here\n    // ...\n} finally {\n    await txn.discard();\n    // ...\n}\n```\n\nYou can make queries read-only and best effort by passing `options` to `DgraphClient#newTxn`. For example:\n\n```js\nconst options = { readOnly: true, bestEffort: true };\nconst res = await dgraphClient.newTxn(options).query(query);\n```\n\nRead-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.\n\n### Run a mutation\n\n`Txn#mutate(Mutation)` runs a mutation. It takes in a `Mutation` object, which\nprovides two main ways to set data: JSON and RDF N-Quad. You can choose whichever\nway is convenient.\n\nWe define a person object to represent a person and use it in a `Mutation` object.\n\n```js\n// Create data.\nconst p = {\n    name: \"Alice\",\n};\n\n// Run mutation.\nawait txn.mutate({ setJson: p });\n```\n\nFor a more complete example with multiple fields and relationships, look at the\n[simple] project in the `examples` folder.\n\nFor setting values using N-Quads, use the `setNquads` field. For delete mutations,\nuse the `deleteJson` and `deleteNquads` fields for deletion using JSON and N-Quads\nrespectively.\n\nSometimes, you only want to commit a mutation, without querying anything further.\nIn such cases, you can use `Mutation#commitNow = true` to indicate that the\nmutation must be immediately committed.\n\n```js\n// Run mutation.\nawait txn.mutate({ setJson: p, commitNow: true });\n```\n\n### Run a query\n\nYou can run a query by calling `Txn#query(string)`. You will need to pass in a\nGraphQL+- query string. If you want to pass an additional map of any variables that\nyou might want to set in the query, call `Txn#queryWithVars(string, object)` with\nthe variables object as the second argument.\n\nThe response would contain the `data` field, `Response#data`, which returns the response\nJSON.\n\nLet’s run the following query with a variable \\$a:\n\n```console\nquery all($a: string) {\n  all(func: eq(name, $a))\n  {\n    name\n  }\n}\n```\n\nRun the query and print out the response:\n\n```js\n// Run query.\nconst query = `query all($a: string) {\n  all(func: eq(name, $a))\n  {\n    name\n  }\n}`;\nconst vars = { $a: \"Alice\" };\nconst res = await dgraphClient.newTxn().queryWithVars(query, vars);\nconst ppl = res.data;\n\n// Print results.\nconsole.log(`Number of people named \"Alice\": ${ppl.all.length}`);\nppl.all.forEach(person =\u003e console.log(person.name));\n```\n\nThis should print:\n\n```console\nNumber of people named \"Alice\": 1\nAlice\n```\n\n### Commit a transaction\n\nA transaction can be committed using the `Txn#commit()` method. If your transaction\nconsisted solely of calls to `Txn#query` or `Txn#queryWithVars`, and no calls to\n`Txn#mutate`, then calling `Txn#commit()` is not necessary.\n\nAn error will be returned if other transactions running concurrently modify the same\ndata that was modified in this transaction. It is up to the user to retry\ntransactions when they fail.\n\n```js\nconst txn = dgraphClient.newTxn();\ntry {\n    // ...\n    // Perform any number of queries and mutations\n    // ...\n    // and finally...\n    await txn.commit();\n} catch (e) {\n    if (e === dgraph.ERR_ABORTED) {\n        // Retry or handle exception.\n    } else {\n        throw e;\n    }\n} finally {\n    // Clean up. Calling this after txn.commit() is a no-op\n    // and hence safe.\n    await txn.discard();\n}\n```\n\n### Check request latency\n\nTo see the server latency information for requests, check the\n`extensions.server_latency` field from the Response object for queries or from\nthe Assigned object for mutations. These latencies show the amount of time the\nDgraph server took to process the entire request. It does not consider the time\nover the network for the request to reach back to the client.\n\n```js\n// queries\nconst res = await txn.queryWithVars(query, vars);\nconsole.log(res.extensions.server_latency);\n// { parsing_ns: 29478,\n//  processing_ns: 44540975,\n//  encoding_ns: 868178 }\n\n// mutations\nconst assigned = await txn.mutate({ setJson: p });\nconsole.log(assigned.extensions.server_latency);\n// { parsing_ns: 132207,\n//   processing_ns: 84100996 }\n```\n\n### Debug mode\n\nDebug mode can be used to print helpful debug messages while performing alters,\nqueries and mutations. It can be set using the`DgraphClient#setDebugMode(boolean?)`\nmethod.\n\n```js\n// Create a client.\nconst dgraphClient = new dgraph.DgraphClient(...);\n\n// Enable debug mode.\ndgraphClient.setDebugMode(true);\n// OR simply dgraphClient.setDebugMode();\n\n// Disable debug mode.\ndgraphClient.setDebugMode(false);\n```\n\n## Development\n\n### Building the source\n\n```sh\nnpm run build\n```\n\n### Running tests\n\nThe script `run-tests.sh` spins up a local cluster and runs the npm tests.\n\n```sh\nbash scripts/run-tests.sh\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdgraph-io%2Fdgraph-js-http","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdgraph-io%2Fdgraph-js-http","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdgraph-io%2Fdgraph-js-http/lists"}