{"id":13517009,"url":"https://github.com/fauna/faunadb-js","last_synced_at":"2025-05-14T04:06:39.117Z","repository":{"id":2705330,"uuid":"43472750","full_name":"fauna/faunadb-js","owner":"fauna","description":"Javascript driver for Fauna v4 (deprecated)","archived":false,"fork":false,"pushed_at":"2024-12-18T16:46:51.000Z","size":32733,"stargazers_count":700,"open_issues_count":27,"forks_count":71,"subscribers_count":36,"default_branch":"v4","last_synced_at":"2025-05-10T03:06:34.419Z","etag":null,"topics":["deprecated"],"latest_commit_sha":null,"homepage":"https://docs.fauna.com/fauna/v4/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fauna.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2015-10-01T01:36:40.000Z","updated_at":"2025-05-05T16:48:04.000Z","dependencies_parsed_at":"2023-07-05T18:49:33.244Z","dependency_job_id":"746fce0e-e48e-4bd7-b7ed-6f99720eaf54","html_url":"https://github.com/fauna/faunadb-js","commit_stats":{"total_commits":797,"total_committers":69,"mean_commits":11.55072463768116,"dds":0.8557089084065245,"last_synced_commit":"3940ad9e71907b7795fd975ae16c9392a679b053"},"previous_names":[],"tags_count":59,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fauna%2Ffaunadb-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fauna%2Ffaunadb-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fauna%2Ffaunadb-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fauna%2Ffaunadb-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fauna","download_url":"https://codeload.github.com/fauna/faunadb-js/tar.gz/refs/heads/v4","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254067578,"owners_count":22009215,"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":["deprecated"],"created_at":"2024-08-01T05:01:28.453Z","updated_at":"2025-05-14T04:06:38.569Z","avatar_url":"https://github.com/fauna.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Back-End Development"],"sub_categories":[],"readme":"# JavaScript driver for Fauna v4 (deprecated)\n\n[![CircleCI](https://circleci.com/gh/fauna/faunadb-js.svg?style=svg)](https://circleci.com/gh/fauna/faunadb-js)\n[![Npm Version](https://img.shields.io/npm/v/faunadb.svg?maxAge=21600)](https://www.npmjs.com/package/faunadb)\n[![License](https://img.shields.io/badge/license-MPL_2.0-blue.svg?maxAge=2592000)](https://raw.githubusercontent.com/fauna/faunadb-js/main/LICENSE)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n\n\u003e [!WARNING]\n\u003e  Fauna is decommissioning FQL v4 on June 30, 2025.\n\u003e\n\u003e This driver is not compatible with FQL v10, the latest version. Fauna accounts\n\u003e created after August 21, 2024 must use FQL v10. Ensure you migrate existing\n\u003e projects to the official v10 driver by the v4 EOL date:\n\u003e https://github.com/fauna/fauna-js.\n\u003e\n\u003e For more information, see the [v4 end of life (EOL)\n\u003e announcement](https://docs.fauna.com/fauna/v4/#fql-v4-end-of-life) and\n\u003e [related FAQ](https://docs.fauna.com/fauna/v4/migration/faq).\n\nThe official JavaScript driver for [Fauna v4](https://docs.fauna.com/fauna/v4/).\n\n[View reference JSDocs here](https://fauna.github.io/faunadb-js).\n\nSee the [FaunaDB Documentation](https://docs.fauna.com/fauna/v4) and\n[Tutorials](https://docs.fauna.com/fauna/v4/learn/tutorials/fql/crud?lang=javascript) for\nguides and a complete database [API\nreference](https://docs.fauna.com/fauna/v4/api/fql/).\n\n## Supported Runtimes\n\nThis Driver supports and is tested on:\n\n- Node.js [*Current*, *Active LTS*, and *Maintenance LTS* releases](https://nodejs.org/en/about/releases/)\n  - *Current* - v17\n  - *Active LTS* - currently v16\n  - *Maintenance LTS* - v12 and v14\n- Chrome\n- Firefox\n- Safari\n- Internet Explorer 11\n\n## Using the Client\n\n### Installation\n\n#### Node.js\n\n`npm install --save faunadb`\n\nor\n\n`yarn add faunadb`\n\n#### Browsers\n\nVia CDN:\n\n```html\n\u003cscript src=\"//cdn.jsdelivr.net/npm/faunadb@latest/dist/faunadb.js\"\u003e\u003c/script\u003e\n```\n\nThe minified version of the driver can also be used via CDN:\n\n```html\n\u003cscript src=\"//cdn.jsdelivr.net/npm/faunadb@latest/dist/faunadb-min.js\"\u003e\u003c/script\u003e\n```\n\n### Use\n\nThe [tutorials](https://docs.fauna.com/fauna/current/learn/tutorials/fql/crud?lang=javascript) in\nthe FaunaDB documentation contain other driver-specific examples.\n\n#### Connecting from the browser\n\nTo get up and running quickly, below is a full example for connecting from the browser. Replace \u003cyour_key_here\u003e with a database secret. You can get that by visiting your [FaunaDB Dashboard](https://v4.dashboard.fauna.com/), creating a new database, clicking on \"Security\" in the sidebar on the left, and then clicking \"New Key\". To learn more about keys, see [FaunaDB Key System](https://docs.fauna.com/fauna/v4/security/keys.html).\n\n```javascript\n\u003chtml\u003e\n  \u003chead\u003e\n  \u003c/head\u003e\n\u003cbody\u003e\n  \u003ch1\u003eTest\u003c/h1\u003e\n\u003c/body\u003e\n\u003cscript src=\"https://cdn.jsdelivr.net/npm/faunadb@latest/dist/faunadb.js\"\u003e\u003c/script\u003e\n\u003cscript type=\"text/javascript\"\u003e\n  var faunadb = window.faunadb\n  var q = faunadb.query\n  var client = new faunadb.Client({\n    secret: 'your_key_here',\n    domain: 'db.fauna.com',\n    scheme: 'https',\n  })\n  client.query(\n    q.ToDate('2018-06-06')\n  )\n  .then(function (res) { console.log('Result:', res) })\n  .catch(function (err) { console.log('Error:', err) })\n\u003c/script\u003e\n\u003c/html\u003e\n```\n\n#### Requiring the Driver\n\n```javascript\nvar faunadb = require('faunadb'),\n  q = faunadb.query\n```\n\nThis is the recommended require stanza. The `faunadb.query` module contains all\nof the functions to create FaunaDB Query expressions.\n\n#### Instantiating a Client and Issuing Queries\n\n```javascript\nvar client = new faunadb.Client({ secret: 'YOUR_FAUNADB_SECRET' })\n```\n\nOnce the client has been instantiated, it can be used to issue queries. For\nexample, to create an document in an existing collection named `test` with the data:\n`{ testField: 'testValue' }`:\n\n```javascript\nvar createP = client.query(\n  q.Create(q.Collection('test'), { data: { testField: 'testValue' } })\n)\n```\n\nAll methods on `faunadb.Client` return [ES6 Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\nSo, if we wanted to handle the Promise to access the `Ref` of the newly created\ndocument:\n\n```javascript\ncreateP.then(function(response) {\n  console.log(response.ref) // Would log the ref to console.\n})\n```\n\n`response` is a JSON object containing the FaunaDB response. See the JSDocs for\n`faunadb.Client`.\n\nThe `metrics` option is used during instantiation to create a client that also\nreturns usage information about the queries issued to FaunaDB.\n\n```javascript\nlet client = new faunadb.Client({\n  secret: 'YOUR_FAUNADB_SECRET',\n  metrics: true\n})\n```\n\n#### Querying and Returning the metrics of your queries\n\nThe `response` object is shaped differently for clients when calling `queryWithMetrics`;\nit includes the value of the response along with a metrics field giving data on ops,\ntime, and transaction retires consumed by your query:\n\n```javascript\n{\n  value: { ... }, // structured response body\n  metrics: {\n    x-compute-ops: XX,\n    x-byte-read-ops: XX,\n    x-byte-write-ops: XX,\n    x-query-time: XX,\n    x-txn-retries: XX\n  } // usage data\n}\n```\n\nMetrics returned in the response will be of `number` data type.\n\n#### Pagination Helpers\n\nThis driver contains helpers to provide a simpler API for consuming paged\nresponses from FaunaDB. See the [Paginate function\nreference](https://docs.fauna.com/fauna/v4/api/fql/functions/paginate)\nfor a description of paged responses.\n\nUsing the helper to page over sets lets the driver handle cursoring and\npagination state. For example, `client.paginate`:\n\n```javascript\nvar helper = client.paginate(q.Match(q.Index('test_index'), 'example-term'))\n```\n\nThe return value, `helper`, is an instance of `PageHelper`. The `each` method will execute a\ncallback function on each consumed page.\n\n```javascript\nhelper.each(function(page) {\n  console.log(page) // Will log the page's contents, for example: [ Ref(\"collections/test/1234\"), ... ]\n})\n```\n\nNote that `each` returns a `Promise\u003cvoid\u003e` that is fulfilled on the completion\nof pagination.\n\nThe pagination can be transformed server-side via the FaunaDB query language\nvia the `map` and `filter` functions.\n\nFor example, to retrieve the matched documents:\n\n```javascript\nhelper\n  .map(function(ref) {\n    return q.Get(ref)\n  })\n  .each(function(page) {\n    console.log(page) // Will now log the retrieved documents.\n  })\n```\n\n[See the JSDocs](https://fauna.github.io/faunadb-js/PageHelper.html) for\nmore information on the pagination helper.\n\n#### Timeouts\n\nThe client can be configured to handle timeouts in two different ways:\n\n1. Add a `timeout` field to the `options` block when instantiating the client\n2. By setting a `queryTimeout` on the client (or passing the value to the client's `.query()` method directly)\n\nThe first option (i.e. `timeout`) represents a HTTP timeout on the client side. Defined in seconds, the client will wait the specified period before timing out if it has yet to receive a response.\n\n```javascript\nconst client = new faunadb.Client({\n  secret: 'YOUR_FAUNADB_SECRET',\n  timeout: 100,\n})\n```\n\nOn the other hand, using the client's `queryTimeout` dictates how long FaunaDB will process the request on the server before timing out if it hasn't finished running the operation. This can be done in two different ways:\n\n```javascript\n// 1. Setting the value when instantiating a new client\nconst client = new faunadb.Client({\n  queryTimeout: 2000,\n  secret: 'YOUR_FAUNADB_SECRET',\n})\n\n// 2. Specifying the value per-query\nvar data = client.query(q.Paginate(q.Collections()), {\n  queryTimeout: 100,\n})\n```\n\n**Note:** When passing a `queryTimeout` value to `client.query()` as part of the `options` object, it will take precendence over any value set on the client when instantiating it.\n\n#### Per-query options\n\nSome options can be provided on a per-query basis:\n\n##### secret\n```javascript\nvar createP = client.query(\n  q.Create(q.Collection('test'), { data: { testField: 'testValue' } }),\n  { secret: 'YOUR_FAUNADB_SECRET' }\n)\n```\n\n```javascript\nvar helper = client.paginate(\n  q.Match(q.Index('test_index'), 'example-term'),\n  null,\n  {\n    secret: 'YOUR_FAUNADB_SECRET',\n  }\n)\n```\n\n##### queryTimeout\n```javascript\nvar data = client.query(q.Paginate(q.Collections()), {\n  queryTimeout: 100,\n})\n```\n\n##### traceparent\nA [W3C-compliant](https://w3c.github.io/trace-context) identifier for enabling distributed tracing across different\nvendors. If not provided, one is automatically generated server-side and attached to the query. Customer's should\ninspect the returned traceresponse to determine if a new traceparent has been created, and use that instead. See\n[Trace Context](https://w3c.github.io/trace-context) spec for more details.\n```javascript\nvar data = client.query(q.Paginate(q.Collections()), {\n  traceparent: \"00-c91308c112be8448dd34dc6191567fa0-b7ad6b7169203331-01\",\n})\n```\n\n##### tags\nAllows for associating user-provided tags with a query.\n```javascript\nvar data = client.query(q.Paginate(q.Collections()), {\n  tags: { key1: \"value1\", key2: \"value2\" },\n})\n```\nBoth tags and their associated values, must be strings. The only allowable characters are alphanumeric values as well\nas an underscope (_). Max length for keys is 40 characters. Max length for values is 60 characters.\n\n#### Custom Fetch\n\nTo use a custom `fetch()` you just have to specify it in the configuration and make it compatible with the [standard Web API Specification of the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n\n```javascript\nconst customFetch = require('./customFetch')\nconst client = new faunadb.Client({\n  secret: 'YOUR_FAUNADB_SECRET',\n  fetch: customFetch,\n})\n```\n\n#### HTTP/2 Session Idle Time (Node.js only)\n\nWhen running on the Node.js platform, the Fauna client uses [HTTP/2 multiplexing](https://stackoverflow.com/questions/36517829/what-does-multiplexing-mean-in-http-2)\nto reuse the same session for many simultaneous requests. After all open requests\nhave been resolved, the client will keep the session open for a period of time\n(500ms by default) to be reused for any new requests.\n\nThe `http2SessionIdleTime` parameter may be used to control how long the HTTP/2\nsession remains open while the query connection is idle. To save on the overhead of\nclosing and re-opening the session, set `http2SessionIdleTime` to a longer time.\nThe default value is 500ms and the maximum value is 5000ms.\n\nNote that `http2SessionIdleTime` has no effect on a stream connection: a stream\nis a long-lived connection that is intended to be held open indefinitely.\n\nWhile an HTTP/2 session is alive, the client holds the Node.js event loop\nopen; this prevents the process from terminating. Call `Client#close` to manually\nclose the session and allow the process to terminate. This is particularly\nimportant if `http2SessionIdleTime` is long:\n\n```javascript\n// sample.js (run it with \"node sample.js\" command)\nconst { Client, query: Q } = require('faunadb')\n\nasync function main() {\n  const client = new Client({\n    secret: 'YOUR_FAUNADB_SECRET',\n    http2SessionIdleTime: 1000, // Must be a non-negative integer\n  })\n  const output = await client.query(Q.Add(1, 1))\n\n  console.log(output)\n\n  client.close()\n}\n\nmain().catch(console.error)\n```\n\n## Known issues\n\n### Using with Cloudflare Workers\n\nCloudflare Workers have neither XMLHttpRequest nor fetch in the global scope.\nTherefore, the `cross-fetch` package is unable to inject its own `fetch()` function, and throws an error.\nThe `fetch()` function is injected via a closure, so the workaround would be to pass\nthe fetch objects when initiating the FaunaDB client config. Cloudflare Workers also\ndoesn't support the use of an AbortController, which terminates requests as well as streams.\nHere is a workaround:\n\n```javascript\nconst c = new faunadb.Client({\n  secret: 'your secret',\n  fetch: (url, params) =\u003e {\n    const signal = params.signal\n    delete params.signal\n    const abortPromise = new Promise(resolve =\u003e {\n      if (signal) {\n        signal.onabort = resolve\n      }\n    })\n    return Promise.race([abortPromise, fetch(url, params)])\n  },\n})\n```\n\n## Client Development\n\nRun `yarn` to install dependencies.\n\n### Code\n\nThis project includes no polyfills. Support for Internet Explorer 11 requires\na `Promise` polyfill.\n\n### Testing\n\nThe driver tests need to connect to a FaunaDB so we recommend you setup one locally. The fast way is running a docker image like `docker run --rm --name faunadb -p 8443:8443 fauna/faunadb`.\n\nAfter have the faunadb working on local you have to setup a set of env variables before run the tests. You can set them manually or use a `.env` file for this.\n\n```bash\nFAUNA_DOMAIN=localhost\nFAUNA_SCHEME=http\nFAUNA_PORT=8443\nFAUNA_ROOT_KEY=secret\nAUTH_0_URI=https://{TENANT}.auth0.com/\nAUTH_0_TOKEN=auth0 token\n```\n\n[Guide for Auth0](https://auth0.com/docs/tokens/management-api-access-tokens/create-and-authorize-a-machine-to-machine-application)\n\n- `yarn test`: This will run tests against the current version of Node.js.\n  [nvm](https://github.com/creationix/nvm) is useful for managing multiple\n  versions of Node.js for testing.\n\nEach test run will create a new database, and will attempt to clean it up when\ndone. If the tests are cancelled, the test database will not get cleaned up.\nTherefore it is recommended to use a FaunaDB key scoped to an empty parent\ndatabase created for this purpose, rather than your account's root key. This\nwill make cleanup of test databases as easy as removing the parent database.\n\nSee the [FaunaDB Multi-tenancy\nTutorial](https://docs.fauna.com/fauna/v4/learn/tutorials/fql/multitenant)\nfor more information about nested databases.\n\nAlternatively, tests can be run via a Docker container with\n`FAUNA_ROOT_KEY=\"your-cloud-secret\" make docker-test` (an alternate\nAlpine-based NodeJS image can be provided via `RUNTIME_IMAGE`).\n\n### Documentation\n\n- `yarn doc` will generate JSDoc documentation for the project.\n\n### Previewing upcoming functionality\n\nIf you want to preview unreleased features in your project, you can do so by installing this driver using one of the following methods.\n\n#### 1. Using a git URL\n\nNormally, you would install the latest release of this package using `npm install --save faunadb` or `yarn add faunadb`. To access our latest features, you will need to define this dependency [by using a git URL](https://docs.npmjs.com/files/package.json#dependencies).\n\n1. Open your `package.json` file\n\n2. If you have already installed this driver, you should see the following in your list of dependencies. If not, add it.\n\n```\n\"faunadb\": \"^2.14.1\"\n```\n\n3. Instead of using a version from the npm registry, we'll want to point our `package.json` to the `main` branch of our GitHub repo. To do that, change the `^2.4.1` to `fauna/faunadb-js#main`.\n\n```\n\"faunadb\": \"fauna/faunadb-js#main\"\n```\n\n4. Update your `node_modules` by running `npm install` or `yarn`\n\n#### 2. Using `npm pack`\n\n1. Clone this repo to your local system\n\n```bash\ngit clone https://github.com/fauna/faunadb-js.git\n```\n\n2. Navigate to the cloned repo and open the `package.json`\n\n```bash\ncd faunadb-js\ncode package.json\n```\n\n3. Change the `version` to be semantic. For example, `3.0.0-beta`.\n\n4. Run `npm pack`. This creates a tarball at the root of your project directory which represents the image sent to the NPM registry when publishing.\n\n5. In another project, you can now install the beta from the local image you just created by running:\n\n```bash\nnpm install /path/to/tarball\n```\n\n## License\n\nCopyright 2023 [Fauna, Inc.](https://fauna.com/)\n\nLicensed under the Mozilla Public License, Version 2.0 (the \"License\"); you may\nnot use this software except in compliance with the License. You may obtain a\ncopy of the License at\n\n[http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/)\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffauna%2Ffaunadb-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffauna%2Ffaunadb-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffauna%2Ffaunadb-js/lists"}