{"id":24343120,"url":"https://github.com/hypermodeinc/dgraph-js","last_synced_at":"2025-05-15T00:12:51.881Z","repository":{"id":27393191,"uuid":"113732772","full_name":"hypermodeinc/dgraph-js","owner":"hypermodeinc","description":"Official Dgraph JavaScript client","archived":false,"fork":false,"pushed_at":"2025-04-06T17:02:31.000Z","size":2272,"stargazers_count":330,"open_issues_count":0,"forks_count":52,"subscribers_count":24,"default_branch":"main","last_synced_at":"2025-05-12T22:44:11.448Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","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/hypermodeinc.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","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,"zenodo":null}},"created_at":"2017-12-10T07:53:49.000Z","updated_at":"2025-05-03T01:14:11.000Z","dependencies_parsed_at":"2024-04-12T14:42:38.046Z","dependency_job_id":"67a3b4aa-4aed-4d31-8007-c43dcb91a03f","html_url":"https://github.com/hypermodeinc/dgraph-js","commit_stats":{"total_commits":281,"total_committers":23,"mean_commits":"12.217391304347826","dds":0.6120996441281139,"last_synced_commit":"dc08ab4bd0f00ca85904fbf358d700f6f392b40e"},"previous_names":["hypermodeinc/dgraph-js","dgraph-io/dgraph-js"],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgraph-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgraph-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgraph-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgraph-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hypermodeinc","download_url":"https://codeload.github.com/hypermodeinc/dgraph-js/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254249206,"owners_count":22039029,"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":[],"created_at":"2025-01-18T08:02:35.315Z","updated_at":"2025-05-15T00:12:46.863Z","avatar_url":"https://github.com/hypermodeinc.png","language":"JavaScript","readme":"# dgraph-js [![npm version](https://img.shields.io/npm/v/dgraph-js.svg?style=flat)](https://www.npmjs.com/package/dgraph-js)\n\nOfficial Dgraph client implementation for JavaScript, using [gRPC].\n\n**Looking for browser support? Check out [dgraph-js-http].**\n\n[grpc]: https://grpc.io/\n[dgraph-js-http]: https://github.com/hypermodeinc/dgraph-js-http\n\nThis client follows the [Dgraph Go client](https://github.com/dgraph-io/dgo) closely.\n\nBefore using this client, we highly recommend that you go through\n[dgraph.io/docs](https://dgraph.io/docs), and understand how to run and work with Dgraph.\n\n## Install\n\nInstall using npm:\n\n```sh\nnpm install dgraph-js @grpc/grpc-js --save\n# If you are using Typescript, you might also need:\n# npm install @types/google-protobuf @types/protobufjs --save-dev\n```\n\nor yarn:\n\n```sh\nyarn add dgraph-js @grpc/grpc-js\n# If you are using Typescript, you might also need:\n# yarn add @types/google-protobuf @types/protobufjs --dev\n```\n\n## Supported Versions\n\nDepending on the version of Dgraph that you are connecting to, you will have to use a different\nversion of this client.\n\n| Dgraph version | dgraph-js version |\n| :------------: | :---------------: |\n|    20.03.0     |     _20.03.0_     |\n|    21.03.0     |     _21.03.0_     |\n|   \u003e=21.03.0    |    \u003e=_21.03.0_    |\n|    \u003e=24.X.X    |    \u003e=_24.X.X_     |\n\n## Quickstart\n\nBuild and run the [simple][] project in the `examples` folder, which contains an end-to-end example\nof using the Dgraph JavaScript client. Follow the instructions in the README of that project.\n\n## Using a Client\n\n### Creating a Client\n\n#### Connection Strings\n\nThe dgraph-js supports connecting to a Dgraph cluster using connection strings. Dgraph connections\nstrings take the form `dgraph://{username:password@}host:port?args`.\n\n`username` and `password` are optional. If username is provided, a password must also be present. If\nsupplied, these credentials are used to log into a Dgraph cluster through the ACL mechanism.\n\nValid connection string args:\n\n| Arg         | Value                           | Description                                                                                                                                                   |\n| ----------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| apikey      | \\\u003ckey\\\u003e                         | a Dgraph Cloud API Key                                                                                                                                        |\n| bearertoken | \\\u003ctoken\\\u003e                       | an access token                                                                                                                                               |\n| sslmode     | disable \\| require \\| verify-ca | TLS option, the default is `disable`. If `verify-ca` is set, the TLS certificate configured in the Dgraph cluster must be from a valid certificate authority. |\n\n## Some example connection strings\n\n| Value                                                                                                        | Explanation                                                                         |\n| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| dgraph://localhost:9080                                                                                      | Connect to localhost, no ACL, no TLS                                                |\n| dgraph://sally:supersecret@dg.example.com:443?sslmode=verify-ca                                              | Connect to remote server, use ACL and require TLS and a valid certificate from a CA |\n| dgraph://foo-bar.grpc.us-west-2.aws.cloud.dgraph.io:443?sslmode=verify-ca\u0026apikey=\\\u003cyour-api-connection-key\\\u003e | Connect to a Dgraph Cloud cluster                                                   |\n| dgraph://foo-bar.grpc.hypermode.com?sslmode=verify-ca\u0026bearertoken=\\\u003csome access token\\\u003e                      | Connect to a Dgraph cluster protected by a secure gateway                           |\n\nUsing the `open` function with a connection string:\n\n```js\n// open a connection to an ACL-enabled, non-TLS cluster and login as groot\nconst client = await dgraph.open(\"dgraph://groot:password@localhost:8090\")\n// Use the client\n\n// this will close all the client stubs\nclient.close()\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,\n`dgraph-js` provides a new method `loginIntoNamespace()`, which will allow the users to login to a\nspecific namespace.\n\nIn order to create a JavaScript client, and make the client login into namespace `123`:\n\n```js\nconst dgraphClientStub = new dgraph.DgraphClientStub(\"localhost:9080\")\nawait dgraphClientStub.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\n`password`. Once logged in, the client can perform all the operations allowed to the `groot` user of\nnamespace `123`.\n\n### Altering the Database\n\nTo set the schema, create an `Operation` object, set the schema and pass it to\n`DgraphClient#alter(Operation)` method.\n\n```js\nconst schema = \"name: string @index(exact) .\"\nconst op = new dgraph.Operation()\nop.setSchema(schema)\nawait dgraphClient.alter(op)\n```\n\nStarting Dgraph version 20.03.0, indexes can be computed in the background. You can set\n`setRunInBackground` field of the `Operation` object to `true` before passing it to the\n`DgraphClient#alter(Operation)` method. You can find more details\n[here](https://docs.dgraph.io/master/query-language/#indexes-in-background).\n\n```js\nconst schema = \"name: string @index(exact) .\"\nconst op = new dgraph.Operation()\nop.setSchema(schema)\nop.setRunInBackground(true)\nawait dgraphClient.alter(op)\n```\n\n\u003e NOTE: Many of the examples here use the `await` keyword which requires `async/await` support which\n\u003e is available on Node.js \u003e= v7.6.0. For prior versions, the expressions following `await` can be\n\u003e used just like normal `Promise`:\n\u003e\n\u003e ```js\n\u003e dgraphClient.alter(op)\n\u003e     .then(function(result) { ... }, function(err) { ... })\n\u003e ```\n\n`Operation` contains other fields as well, including drop predicate and drop all. Drop all is useful\nif you wish to discard all the data, and start from a clean slate, without bringing the instance\ndown.\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.\nconst op = new dgraph.Operation()\nop.setDropAll(true)\nawait dgraphClient.alter(op)\n```\n\n### Creating a Transaction\n\nTo create a transaction, call `DgraphClient#newTxn()` method, which returns a new `Txn` object. This\noperation incurs no network overhead.\n\nIt is good practise to call `Txn#discard()` in a `finally` block after running the transaction.\nCalling `Txn#discard()` after `Txn#commit()` is a no-op and you can call `Txn#discard()` multiple\ntimes 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\nTo create a read-only transaction, set `readOnly` boolean to `true` while calling\n`DgraphClient#newTxn()` method. Read-only transactions cannot contain mutations and trying to call\n`Txn#mutate()` or `Txn#commit()` will result in an error. Calling `Txn.Discard()` will be a no-op.\n\nYou can optionally set the `bestEffort` boolean to `true`. This may yield improved latencies in\nread-bound workloads where linearizable reads are not strictly needed.\n\n```js\nconst txn = dgraphClient.newTxn({\n  readOnly: true,\n  bestEffort: false,\n})\n// ...\nconst res = await txn.queryWithVars(query, vars)\n```\n\n### Running a Mutation\n\n`Txn#mutate(Mutation)` runs a mutation. It takes in a `Mutation` object, which provides two main\nways to set data: JSON and RDF N-Quad. You can choose whichever way 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.\nconst mu = new dgraph.Mutation()\nmu.setSetJson(p)\nawait txn.mutate(mu)\n```\n\nFor a more complete example with multiple fields and relationships, look at the [simple] project in\nthe `examples` folder.\n\nSometimes, you only want to commit a mutation, without querying anything further. In such cases, you\ncan use `Mutation#setCommitNow(true)` to indicate that the mutation must be immediately committed.\n\n`Mutation#setIgnoreIndexConflict(true)` can be applied on a `Mutation` object to not run conflict\ndetection over the index, which would decrease the number of transaction conflicts and aborts.\nHowever, this would come at the cost of potentially inconsistent upsert operations.\n\nMutation can be run using `txn.doRequest` as well.\n\n```js\nconst mu = new dgraph.Mutation()\nmu.setSetJson(p)\n\nconst req = new dgraph.Request()\nreq.setCommitNow(true)\nreq.setMutationsList([mu])\n\nawait txn.doRequest(req)\n```\n\n### Running a Query\n\nYou can run a query by calling `Txn#query(string)`. You will need to pass in a GraphQL+- query\nstring. If you want to pass an additional map of any variables that you might want to set in the\nquery, call `Txn#queryWithVars(string, object)` with the variables object as the second argument.\n\nThe response would contain the method `Response#getJSON()`, which returns the response JSON.\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, deserialize the result from Uint8Array (or base64) encoded JSON and print it out:\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.getJson()\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\nYou can also use `txn.doRequest` function to run the query.\n\n```js\nconst req = new dgraph.Request()\nconst vars = req.getVarsMap()\nvars.set(\"$a\", \"Alice\")\nreq.setQuery(query)\n\nconst res = await txn.doRequest(req)\nconsole.log(JSON.stringify(res.getJson()))\n```\n\n### Running an Upsert: Query + Mutation\n\nThe `txn.doRequest` function allows you to run upserts consisting of one query and one mutation.\nQuery variables could be defined and can then be used in the mutation. You can also use the\n`txn.doRequest` function to perform just a query or a mutation.\n\nTo know more about upsert, we highly recommend going through the docs at\nhttps://docs.dgraph.io/mutations/#upsert-block.\n\n```js\nconst query = `\n  query {\n      user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n  }`\n\nconst mu = new dgraph.Mutation()\nmu.setSetNquads(`uid(user) \u003cemail\u003e \"correct_email@dgraph.io\" .`)\n\nconst req = new dgraph.Request()\nreq.setQuery(query)\nreq.setMutationsList([mu])\nreq.setCommitNow(true)\n\n// Upsert: If wrong_email found, update the existing data\n// or else perform a new mutation.\nawait dgraphClient.newTxn().doRequest(req)\n```\n\n### Running a Conditional Upsert\n\nThe upsert block allows specifying a conditional mutation block using an `@if` directive. The\nmutation is executed only when the specified condition is true. If the condition is false, the\nmutation is silently ignored.\n\nSee more about Conditional Upsert [Here](https://docs.dgraph.io/mutations/#conditional-upsert).\n\n```js\nconst query = `\n  query {\n      user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n  }`\n\nconst mu = new dgraph.Mutation()\nmu.setSetNquads(`uid(user) \u003cemail\u003e \"correct_email@dgraph.io\" .`)\nmu.setCond(`@if(eq(len(user), 1))`)\n\nconst req = new dgraph.Request()\nreq.setQuery(query)\nreq.addMutations(mu)\nreq.setCommitNow(true)\n\nawait dgraphClient.newTxn().doRequest(req)\n```\n\n### Committing a Transaction\n\nA transaction can be committed using the `Txn#commit()` method. If your transaction consisted solely\nof calls to `Txn#query` or `Txn#queryWithVars`, and no calls to `Txn#mutate`, then calling\n`Txn#commit()` is not necessary.\n\nAn error will be returned if other transactions running concurrently modify the same data that was\nmodified in this transaction. It is up to the user to retry transactions 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### Cleanup Resources\n\nTo cleanup resources, you have to call `close()`.\n\n```js\nconst SERVER_ADDR = \"localhost:9080\"\nconst SERVER_CREDENTIALS = grpc.credentials.createInsecure()\n\n// Create instances of DgraphClient.\nconst client = await dgraph.open(\"dgraph://groot:password@${SERVER_ADDR}\")\n\n// ...\n// Use dgraphClient\n// ...\n\n// Cleanup resources by closing client stubs.\nclient.close()\n```\n\n### Debug mode\n\nDebug mode can be used to print helpful debug messages while performing alters, queries and\nmutations. It can be set using the`DgraphClient#setDebugMode(boolean?)` method.\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### Setting Metadata Headers\n\nMetadata headers such as authentication tokens can be set through the context of gRPC methods. Below\nis an example of how to set a header named \"auth-token\".\n\n```js\n// The following piece of code shows how one can set metadata with\n// auth-token, to allow Alter operation, if the server requires it.\n\nvar meta = new grpc.Metadata()\nmeta.add(\"auth-token\", \"mySuperSecret\")\n\nawait dgraphClient.alter(op, meta)\n```\n\n## Examples\n\n- [simple][]: Quickstart example of using dgraph-js.\n- [tls][]: Example of using dgraph-js with a Dgraph cluster secured with TLS.\n\n[simple]: ./examples/simple\n[tls]: ./examples/tls\n\n## Development\n\n### Building the source\n\n```sh\nnpm run build\n```\n\nIf you have made changes to the `proto/api.proto` file, you need need to regenerate the source files\ngenerated by Protocol Buffer tools. To do that, install the [Protocol Buffer Compiler][protoc] and\nthen run the following command:\n\n[protoc]: https://github.com/google/protobuf#readme\n\n```sh\nnpm run build:protos\n```\n\n### Running tests\n\nMake sure you have a Dgraph server running on localhost before you run this task.\n\n```sh\nnpm test\n```\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhypermodeinc%2Fdgraph-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhypermodeinc%2Fdgraph-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhypermodeinc%2Fdgraph-js/lists"}