Class: Client

Client(optionsnullable)

new Client(optionsnullable)

A client for interacting with FaunaDB.

Users will mainly call the Client#query method to execute queries, or the Client#stream method to subscribe to streams.

See the FaunaDB Documentation for detailed examples.

All methods return promises containing a JSON object that represents the FaunaDB response. Literal types in the response object will remain as strings, Arrays, and objects. FaunaDB types, such as Ref, SetRef, FaunaTime, and FaunaDate will be converted into the appropriate object.

(So if a response contains { "@ref": "collections/frogs/123" }, it will be returned as new Ref("collections/frogs/123").)

Parameters:
Name Type Attributes Description
options Object <nullable>

Object that configures this FaunaDB client.

Properties
Name Type Attributes Description
endpoint string <nullable>

Full URL for the FaunaDB server.

domain string <nullable>

Base URL for the FaunaDB server.

scheme 'http' | 'https' <nullable>

HTTP scheme to use.

port number <nullable>

Port of the FaunaDB server.

secret string <nullable>

FaunaDB secret (see Reference Documentation)

timeout number <nullable>

Read timeout in seconds.

observer Client~observerCallback <nullable>

Callback that will be called after every completed request.

keepAlive boolean <nullable>

Configures http/https keepAlive option (ignored in browser environments)

headers Object <nullable>

Optional headers to send with requests

fetch fetch <nullable>

a fetch compatible API for making a request

queryTimeout number <nullable>

Sets the maximum amount of time (in milliseconds) for query execution on the server

http2SessionIdleTime number <nullable>

Sets the maximum amount of time (in milliseconds) an HTTP2 session may live when there's no activity. Must be a non-negative integer, with a maximum value of 5000. If an invalid value is passed a default of 500 ms is applied. If a value exceeding 5000 ms is passed (e.g. Infinity) the maximum of 5000 ms is applied. Only applicable for NodeJS environment (when http2 module is used). can also be configured via the FAUNADB_HTTP2_SESSION_IDLE_TIME environment variable which has the highest priority and overrides the option passed into the Client constructor.

checkNewVersion boolean <nullable>

Enabled by default. Prints a message to the terminal when a newer driver is available.

metrics boolean <nullable>

Disabled by default. Controls whether or not query metrics are returned.

Source:

Members

(static) apiVersion :string

Current API version.

Type:
  • string
Source:

Methods

close(optsnullable) → {Promise.<void>}

Closes the client session and cleans up any held resources. By default, it will wait for any ongoing requests to complete on their own; streaming requests are terminated forcibly. Any subsequent requests will error after the .close method is called. Should be used at application termination in order to release any open resources and allow the process to terminate e.g. when the custom http2SessionIdleTime parameter is used.

Parameters:
Name Type Attributes Description
opts object <nullable>

Close options.

Properties
Name Type Attributes Description
force boolean <nullable>

Specifying this property will force any ongoing requests to terminate instead of gracefully waiting until they complete. This may result in an ERR_HTTP2_STREAM_CANCEL error for NodeJS.

Source:
Returns:
Type
Promise.<void>

getLastTxnTime() → {number}

Get the freshest timestamp reported to this client.

Source:
Returns:

the last seen transaction time

Type
number

paginate(expression, params, optionsnullable) → {PageHelper}

Returns a PageHelper for the given Query expression. This provides a helpful API for paginating over FaunaDB responses.

Parameters:
Name Type Attributes Description
expression Expr

The Query expression to paginate over.

params Object

Options to be passed to the paginate function. See paginate.

options Object <nullable>

Object that configures the current pagination queries, overriding FaunaDB client options.

Properties
Name Type Attributes Description
secret string <nullable>

FaunaDB secret (see Reference Documentation)

Source:
Returns:

A PageHelper that wraps the provided expression.

Type
PageHelper

ping() → {external:Promise.<string>}

Sends a ping request to FaunaDB.

Source:
Returns:

Ping response.

Type
external:Promise.<string>

query(expression, optionsnullable) → {external:Promise.<Object>}

Executes a query via the FaunaDB Query API. See the docs, and the query functions in this documentation.

Parameters:
Name Type Attributes Description
expression module:query~ExprArg

The query to execute. Created from module:query functions.

options Object <nullable>

Object that configures the current query, overriding FaunaDB client options.

Properties
Name Type Attributes Description
secret string <nullable>

FaunaDB secret (see Reference Documentation)

Source:
Returns:

FaunaDB response object.

Type
external:Promise.<Object>

queryWithMetrics(expression, optionsnullable) → {external:Promise.<Object>}

Executes a query via the FaunaDB Query API. See the docs, and the query functions in this documentation.

Parameters:
Name Type Attributes Description
expression module:query~ExprArg

The query to execute. Created from module:query functions.

options Object <nullable>

Object that configures the current query, overriding FaunaDB client options.

Properties
Name Type Attributes Description
secret string <nullable>

FaunaDB secret (see Reference Documentation)

Source:
Returns:

{value, metrics} An object containing the FaunaDB response object and the list of query metrics incurred by the request.

Type
external:Promise.<Object>

stream(expression, optionsnullable) → {module:stream~Subscription}

WARNING: This is an experimental feature. There are no guarantees to its API stability and/or service availability. DO NOT USE IT IN PRODUCTION.

Creates a subscription to the result of the given read-only expression. When executed, the expression must only perform reads and produce a single streamable type, such as a reference or a version. Expressions that attempt to perform writes or produce non-streamable types will result in an error. Otherwise, any expression can be used to initiate a stream, including user-defined function calls.

The subscription returned by this method does not issue any requests until the module:stream~Subscription#start method is called. Make sure to subscribe to the events of interest, otherwise the received events are simply ignored. For example:

client.stream(document.ref)
  .on('version', version => console.log(version))
  .on('error', error => console.log(error))
  .start()

Please note that streams are not temporal, meaning that there is no option to configure its starting timestamp. The stream will, however, state its initial subscription time via the module:stream~Subscription#event:start event. A common programming mistake is to read a document, then initiate a subscription. This approach can miss events that occurred between the initial read and the subscription request. To prevent event loss, make sure the subscription has started before performing a data load. The following example buffer events until the document's data is loaded:

var buffer = []
var loaded = false

client.stream(document.ref)
  .on('start', ts => {
    loadData(ts).then(data => {
      processData(data)
      processBuffer(buffer)
      loaded = true
    })
  })
  .on('version', version => {
    if (loaded) {
      processVersion(version)
    } else {
      buffer.push(version)
    }
  })
  .start()

The reduce boilerplate, the document helper implements a similar functionality, except it discards events prior to the document's snapshot time. The expression given to this helper must be a reference as it internally runs a module:query~Get call with it. The example above can be rewritten as:

client.stream.document(document.ref)
  .on('snapshot', data => processData(data))
  .on('version', version => processVersion(version))
  .start()

Be aware that streams are not available in all browsers. If the client can't initiate a stream, an error event with the module:errors~StreamsNotSupported error will be emmited.

To stop a subscription, call the module:stream~Subscription#close method:

var subscription = client.stream(document.ref)
  .on('version', version => processVersion(version))
  .start()

// ...
subscription.close()
Parameters:
Name Type Attributes Description
expression module:query~ExprArg

The expression to subscribe to. Created from module:query functions.

options module:stream~Options <nullable>

Object that configures the stream.

Properties:
Name Type Description
document function

A document stream helper. See Client#stream for more information.

Source:
See:
Returns:

A new subscription instance.

Type
module:stream~Subscription

syncLastTxnTime(time)

Sync the freshest timestamp seen by this client.

This has no effect if staler than currently stored timestamp. WARNING: This should be used only when coordinating timestamps across multiple clients. Moving the timestamp arbitrarily forward into the future will cause transactions to stall.

Parameters:
Name Type Description
time number

the last seen transaction time

Source:

Type Definitions

observerCallback(res)

The callback that will be executed after every completed request.

Parameters:
Name Type Description
res RequestResult
Source: