From 5f8a1d9f8bdb1afcfd5242e61fe3114c751828f6 Mon Sep 17 00:00:00 2001 From: James Rodewig Date: Wed, 27 Mar 2024 11:42:07 -0400 Subject: [PATCH] [DOCS-2595] Reorganize JS driver README --- README.md | 402 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 206 insertions(+), 196 deletions(-) diff --git a/README.md b/README.md index 64cbe320..d6ab899a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# The Official Javascript Driver for [Fauna](https://fauna.com). +# The Official JavaScript Driver for [Fauna](https://fauna.com). -[![Npm Version](https://img.shields.io/npm/v/fauna.svg?maxAge=21600)](https://www.npmjs.com/package/fauna) +[![npm Version](https://img.shields.io/npm/v/fauna.svg?maxAge=21600)](https://www.npmjs.com/package/fauna) [![License](https://img.shields.io/badge/license-MPL_2.0-blue.svg?maxAge=2592000)](https://raw.githubusercontent.com/fauna/fauna-js/main/LICENSE) This driver can only be used with FQL v10, and is not compatible with earlier versions of FQL. To query your databases with earlier API versions, see the [faunadb](https://www.npmjs.com/package/faunadb) package. @@ -10,53 +10,104 @@ See the [Fauna Documentation](https://docs.fauna.com/fauna/current/) for additio
Table of Contents -- [A JavaScript driver for Fauna.](#a-javascript-driver-for-fauna) -- [Quick-Start](#quick-start) -- [Supported Runtimes](#supported-runtimes) -- [Installation](#installation) - - [Package Manager](#package-manager) - - [Via CDN](#via-cdn) -- [Usage](#usage) - - [Creating queries with the `fql` function](#creating-queries-with-the-fql-function) - - [Connecting from the browser](#connecting-from-the-browser) - - [Importing into a bundled project](#importing-into-a-bundled-project) - - [Typescript Support](#typescript-support) - - [Query Options](#query-options) - - [Client Configuration](#client-configuration) +- [The Official JavaScript Driver for Fauna.](#the-official-javascript-driver-for-fauna) + - [Supported runtimes](#supported-runtimes) + - [Install](#install) + - [Usage](#usage) + - [Write FQL queries](#write-fql-queries) + - [Typescript support](#typescript-support) + - [Query options](#query-options) + - [Query statistics](#query-statistics) + - [Event Streaming (beta)](#event-streaming-beta) + - [Client configuration](#client-configuration) + - [Environment variables](#environment-variables) + - [Retry](#retry) + - [Max attempts](#max-attempts) + - [Max backoff](#max-backoff) - [Timeouts](#timeouts) - - [Query Timeout](#query-timeout) - - [Client Timeout](#client-timeout) - - [HTTP/2 Session Idle Timeout](#http2-session-idle-timeout) - - [Using environment variables](#using-environment-variables) - - [Query Statistics](#query-statistics) -- [Contributing](#contributing) - - [Setting up this Repo](#setting-up-this-repo) - - [Running tests](#running-tests) - - [Linting your code](#linting-your-code) -- [License](#license) + - [Query timeout](#query-timeout) + - [Client timeout](#client-timeout) + - [HTTP/2 session idle timeout](#http2-session-idle-timeout) + - [Contributing](#contributing) + - [Set up the repo](#set-up-the-repo) + - [Run tests](#run-tests) + - [Lint your code](#lint-your-code) + - [License](#license)
-# Quick-Start + +## Supported runtimes + +**Server-side** + +Node.js - [Current and active LTS versions](https://nodejs.org/en/about/releases/): + +- Current - v20 +- LTS - v18 + +**Cloud providers** + +- Cloudflare Workers +- AWS Lambda +- Netlify +- Vercel + +**Browsers** + +Stable versions of: + +- Chrome 69+ +- Firefox 62+ +- Safari 12.1+ +- Edge 79+ + + +## Install + +The driver is available on [npm](https://www.npmjs.com/package/fauna). You +can install it using your preferred package manager. For example: + +```shell +npm install fauna +``` + +Browsers can import the driver using a CDN link: + +```html + +``` + + +## Usage + +By default, the driver's `Client` instance authenticates with Fauna using an +access token in the `FAUNA_SECRET` environment variable. If needed, you can pass +the token to the client using the `secret` argument instead. ```javascript import { Client, fql, FaunaError } from "fauna"; +// Use `require` for CommonJS: +// const { Client, fql, FaunaError } = require('fauna'); -// configure your client -const client = new Client({ - secret: YOUR_FAUNA_SECRET, -}); +const client = new Client(); +// To configure your client: +// const client = new Client({ +// secret: YOUR_FAUNA_SECRET, +// }); try { - // build queries using the `fql` function + // Build a query using the `fql` method const collectionQuery = fql`Collection.create({ name: "Dogs" })`; - // execute the query + // Run the query const collectionResponse = await client.query(collectionQuery); - // define some data in your app + // Declare a var for app data const dog = { name: "Scout" }; - // query using your app's local variables + // Build a query using the var const documentQuery = fql` Dogs.create(${dog}) { id, @@ -65,72 +116,29 @@ try { } `; - // execute the query + // Run the query const response = await client.query(documentQuery); + console.log(response); } catch (error) { if (error instanceof FaunaError) { - // handle errors + console.log(error); } } finally { - // clean up any remaining resources + // Clean up any remaining resources client.close(); } ``` -# Supported Runtimes - -This Driver supports and is tested on: - -- Browsers - Stable versions of - - Chrome 69+ - - Firefox 62+ - - Safari 12.1+ - - Edge 79+ -- Node.js - [Current and Active LTS](https://nodejs.org/en/about/releases/) - - Current - v20 - - LTS - v18 -- Cloudflare Workers -- AWS Lambda -- Netlify -- Vercel - -# Installation - -## Package Manager - -The fauna-js driver is available on npm. You can install with your package manager of choice: - -```shell -npm install fauna -``` -or - -```shell -yarn add fauna -``` - -## Via CDN - -The driver is additionally made available to browsers via CDN: - -```html - -``` - -# Usage - -## Creating queries with the `fql` function +### Write FQL queries The `fql` function is your gateway to building safe, reuseable Fauna queries. It allows you compose queries from sub-queries and variables native to your program. Variables passed in are treated as unexecutable values in Fauna's API - preventing security issues like injection attacks. -for example: +For example: -```typescript +```javascript import { Client, fql } from "fauna"; const client = new Client(); @@ -138,21 +146,22 @@ const client = new Client(); // Variables can be used as arguments in an FQL query const collectionName = "Pets"; -// a reusable sub-query to determine if a collection exists +// Build a reusable sub-query to determine if a collection exists const collectionExists = (name) => fql`Collection.byName(${name}) != null`; -// define a new query that uses the prior sub-query +// Build query that uses the previous var and sub-query const upsertCollectionQuery = fql` if (${collectionExists(collectionName)}) { - "Collection exists!" + "Collection already exists" } else { Collection.create({ name: ${collectionName} }) - "Collection exists now!" + "Collection created" } `; -// execute the query +// Run the query const response = await client.query(upsertCollectionQuery); +console.log(response.data); client.close(); ``` @@ -163,40 +172,13 @@ This has several advantages: - Injection attacks are not possible if you pass input variables into the interpolated (`` `${interpoloated_argument}` ``) parts of the query. - The driver speaks "pure" FQL - you can try out some FQL queries on the dashboard's terminal and paste it directly into your app like `` fql`copied from terminal...` `` and the query will work as is. -## Connecting from the browser - -```html - - - -

Test

- - - -``` - -## Importing into a bundled project - -```javascript -import * as fauna from "fauna"; -``` - -or using `require` for CommonJS files - -```javascript -const fauna = require("fauna"); -``` -## Typescript Support +### Typescript support With TypeScript, you can apply a type parameter to your result. ```typescript -import { Client, fql } from "fauna"; +import { fql, Client, type QuerySuccess } from "fauna"; const client = new Client(); @@ -219,9 +201,11 @@ console.assert(user_doc.email === "alice@site.example"); client.close(); ``` -## Query Options -Options are available to configure queries on each request. +### Query options + +Options are available to configure queries on each request. These override any +default query options in the [client configuration](#client-configuration). ```typescript import { fql, Client, type QueryOptions } from "fauna"; @@ -241,23 +225,80 @@ const options: QueryOptions = { }; const response = await client.query(fql`"Hello, #{name}!"`, options); +console.log(response.data) client.close(); ``` -## Client Configuration -The driver use's a default ClientConfiguration. We recommend most users stick with the defaults. +### Query statistics + +Query statistics are returned with successful query responses and errors of +the `ServiceError` type. + +```typescript +import { + fql, + Client, + ServiceError, + type QueryInfo, + type QueryStats, + type QuerySuccess, +} from "fauna"; + +const client = new Client(); + +try { + const response: QuerySuccess = await client.query( + fql`"Hello world"` + ); + const stats: QueryStats | undefined = response.stats; + console.log(stats); +} catch (error: any) { + if (error instanceof ServiceError) { + const info: QueryInfo = error.queryInfo; + const stats: QueryStats | undefined = info.stats; + } +} +``` + +Example output: + +```javascript +{ + compute_ops: 1, + read_ops: 0, + write_ops: 0, + query_time_ms: 15, + storage_bytes_read: 0, + storage_bytes_write: 0, + contention_retries: 0 +} +``` + + +## Event Streaming (beta) -If your environment needs different configuration however, the default ClientConfiguration can be overridden. +[Event Streaming](https://docs.fauna.com/fauna/current/learn/streaming) is +currently available in the beta version of the driver: -Furthermore, on each request you can provide query specific configuration that will override the setting in your client for that request only. +- [Beta JavaScript driver](https://www.npmjs.com/package/fauna/v/1.4.0-beta.0) +- [Beta JavaScript driver docs](https://github.com/fauna/fauna-js/tree/beta) + + +## Client configuration + +The driver's `Client` instance comes with reasonable defaults that should be +used in most cases. Yu can override these defaults if needed. + +In addition to configuring the client, you can also set default [query +options](#query-options). ```typescript import { Client, endpoints, type ClientConfiguration } from "fauna"; const config: ClientConfiguration = { - // configure client + // Configure the client client_timeout_buffer_ms: 5000, endpoint: endpoints.default, fetch_keepalive: false, @@ -265,7 +306,7 @@ const config: ClientConfiguration = { http2_session_idle_ms: 5000, secret: YOUR_FAUNA_SECRET, - // set default query options + // Set default query options format: "tagged", long_type: "number", linearized: false, @@ -281,23 +322,46 @@ const config: ClientConfiguration = { const client = new Client(config); ``` + +### Environment variables + +The driver will default to configuring your client with the values of the `FAUNA_SECRET` and `FAUNA_ENDPOINT` environment variable. + +For example, if you set the following environment variables: + +```shell +export FAUNA_SECRET=YOUR_FAUNA_SECRET +export FAUNA_ENDPOINT=https://db.fauna.com/ +``` + +You can initalize the client with a default configuration: + +```javascript +const client = new Client(); +``` + + ### Retry -#### Max Attempts + +#### Max attempts The maximum number of times a query will be attempted if a retryable exception is thrown (ThrottlingError). Default 3, inclusive of the initial call. The retry strategy implemented is a simple exponential backoff. To disable retries, pass max_attempts less than or equal to 1. -#### Max Backoff + +#### Max backoff The maximum backoff in seconds to be observed between each retry. Default 20 seconds. + ### Timeouts There are a few different timeout settings that can be configured; each comes with a default setting. We recommend that most applications simply stick to the defaults. -#### Query Timeout + +#### Query timeout The query timeout is the time, in milliseconds, that Fauna will spend executing your query before aborting with a 503 Timeout error. If a query timeout occurs, the driver will throw an instance of `ServiceTimeoutError`. @@ -313,7 +377,8 @@ The query timeout can also be set to a different value for each query using the const response = await client.query(myQuery, { query_timeout_ms: 20_000 }); ``` -#### Client Timeout + +#### Client timeout The client timeout is the time, in milliseconds, that the client will wait for a network response before canceling the request. If a client timeout occurs, the driver will throw an instance of `NetworkError`. @@ -323,7 +388,8 @@ The client timeout is always the query timeout plus an additional buffer. This e const client = new Client({ client_timeout_buffer_ms: 6000 }); ``` -#### HTTP/2 Session Idle Timeout + +#### HTTP/2 session idle timeout The HTTP/2 session idle timeout is the time, in milliseconds, that an HTTP/2 session will remain open after there is no more pending communication. Once the session idle time has elapsed the session is considered idle and the session is closed. Subsequent requests will create a new session; the session idle timeout does not result in an error. @@ -341,68 +407,8 @@ const client = new Client({ http2_session_idle_ms: 6000 }); > **Warning** > Setting `http2_session_idle_ms` to small values can lead to a race condition where requests cannot be transmitted before the session is closed, yielding `ERR_HTTP2_GOAWAY_SESSION` errors. -### Using environment variables -The driver will default to configuring your client with the values of the `FAUNA_SECRET` and `FAUNA_ENDPOINT` environment variable. - -For example, if you set the following environment variables: - -```shell -export FAUNA_SECRET=YOUR_FAUNA_SECRET -export FAUNA_ENDPOINT=https://db.fauna.com/ -``` - -you can create a client without additional options - -```javascript -const client = new Client(); -``` - -## Query Statistics - -Query statistics are returned with successful query responses and `ServiceError`s. - -````typescript -import { - fql, - Client, - ServiceError, - type QueryInfo, - type QueryStats, - type QuerySuccess, -} from "fauna"; - -const client = new Client(); - -try { - const response: QuerySuccess = await client.query( - fql`"Hello world"` - ); - const stats: QueryStats | undefined = response.stats; - console.log(stats); -} catch (error: any) { - if (error instanceof ServiceError) { - const info: QueryInfo = error.queryInfo; - const stats: QueryStats | undefined = info.stats; - } -} - -/* example output - * ``` - * { - * compute_ops: 1, - * read_ops: 0, - * write_ops: 0, - * query_time_ms: 15, - * storage_bytes_read: 0, - * storage_bytes_write: 0, - * contention_retries: 0 - * } - * ``` - */ -```` - -# Contributing +## Contributing Any contributions are from the community are greatly appreciated! @@ -410,22 +416,26 @@ If you have a suggestion that would make this better, please fork the repo and c Don't forget to give the project a star! Thanks again! -## Setting up this Repo + +### Set up the repo 1. Clone the repository; e.g. `gh repo clone fauna/fauna-js` if you use the GitHub CLI 2. Install dependencies via `yarn install` -## Running tests + +### Run tests 1. Start a docker desktop or other docker platform. 2. Run `yarn test`. This will start local fauna containers, verify they're up and run all tests. -## Linting your code + +### Lint your code Linting runs automatically on each commit. If you wish to run on-demand run `yarn lint`. -# License + +## License Distributed under the MPL 2.0 License. See [LICENSE](./LICENSE) for more information.