Class: Client

Client


new Client(options)

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 Argument Description
options Object <nullable>

Object that configures this FaunaDB client.

Properties
Name Type Argument Description
domain string <nullable>

Base URL for the FaunaDB server.

headers Object <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)

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 either be a non-negative integer, or Infinity to allow the HTTP2 session to live indefinitely (use Client#close to manually terminate the client). Only applicable for NodeJS environment (when http2 module is used). Default is 500ms; 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.

Members


<static> apiVersion :string

Current API version.

Type:
  • string

Methods


close(opts)

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 Argument Description
opts object <nullable>

Close options.

Properties
Name Type Argument 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.

Returns:
Type
Promise.<void>

getLastTxnTime()

Get the freshest timestamp reported to this client.

Returns:

the last seen transaction time

Type
number

paginate(expression, params, options)

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

Parameters:
Name Type Argument 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 Argument Description
secret string <nullable>

FaunaDB secret (see Reference Documentation)

Returns:

A PageHelper that wraps the provided expression.

Type
PageHelper

ping()

Sends a ping request to FaunaDB.

Returns:

Ping response.

Type
external:Promise.<string>

query(expression, options)

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

Parameters:
Name Type Argument 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 Argument Description
secret string <nullable>

FaunaDB secret (see Reference Documentation)

Returns:

FaunaDB response object.

Type
external:Promise.<Object>

stream(expression, options)

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 Argument 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.

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

Type Definitions


observerCallback(res)

The callback that will be executed after every completed request.

Parameters:
Name Type Description
res RequestResult