JavaScript driver
The section describes Fauna’s open source JavaScript driver, which provides the resources required to interact with Fauna.
Current stable version |
4.7.1 |
Repository |
Supported runtimes
This driver supports and is tested on:
-
Node.js
-
LTS
-
Stable
-
-
Chrome
-
Firefox
-
Safari
-
Internet Explorer 11
Usage
Requiring the driver
var faunadb = require('faunadb'),
q = faunadb.query
This is the recommended require
stanza. The faunadb.query
module
contains all of the functions to create Fauna Query expressions.
Instantiating a client and issuing queries
var client = new faunadb.Client({ secret: 'YOUR_FAUNADB_SECRET' })
Once the client has been instantiated, it can be used to issue queries.
For example, to create an instance in an existing class named test
with the data: { testField: 'testValue' }
:
var createP = client.query(
q.Create(
q.Collection('test'),
{ data: { testField: 'testValue' } }
)
)
All methods on faunadb.Client
return
ES6
Promises. So, if we wanted to handle the Promise to access the Ref
of the newly created instance:
createP.then(function(response) {
console.log(response.ref); // Logs the ref to the console.
})
response
is a JSON object containing the Fauna response. See the
JSDocs for faunadb.Client
.
By default, the client object executes queries using HTTP Keep-Alive requests, which means that the connection is held open longer than required to receive a query response. This behavior can reduce the connection overhead when your code needs to issue many queries.
Should you ever need to disable keep-alive connections, you can do so in the client constructor’s options:
var client = new faunadb.Client({
secret: 'YOUR_FAUNADB_SECRET',
keepAlive: false,
})
When keepAlive
is set to false
, each query that your code executes
results in a separate HTTP connection to Fauna.
Pagination helpers
The driver contains helpers to provide a simpler API for consuming paged responses from Fauna. See the Paginate reference for a description of paged responses.
Using the helper to page over sets lets the driver manage cursors
and pagination state. For example, client.paginate
:
var helper = client.paginate(
q.Match(
q.Index('test_index'),
'example-term'
)
)
The return value, helper
, is an instance of PageHelper
. The each
method executes a callback function on each consumed page.
helper.each(function(page) {
// Logs the page's contents,
// for example: [ Ref(Collection("test"), "1234"), ... ]
console.log(page);
});
Note that each
returns a Promise<void>
that is fulfilled on the
completion of pagination.
The pagination can be transformed server-side via the Fauna Query Language by using the
map
and filter
functions.
For example, to retrieve the matched instances:
helper
.map(function(ref) {
return q.Get(ref)
})
.each(function(page) {
console.log(page); // Logs the retrieved documents.
})
See the JSDocs for more information on the pagination helper.
Timeouts
The client can be configured to handle timeouts in two different ways:
-
Specify an HTTP timeout in seconds by adding a
timeout
field to theoptions
block when instantiating the client.When
timeout
is provided, the client waits the specified number of seconds before timing out, if it has yet to receive a response. When the period has elapsed, any subsequent response cannot be handled. -
Specify a server query timeout:
-
by adding
queryTimeout
to theoptions
block when instantiating the client, or -
by passing an object containing
queryTimeout
as the second parameter to the.query
method.
When a query timeout is provided, the server waits for the specified number of milliseconds before timing out, if it has yet to complete the current query. When the period has elapsed, the query fails and the server responds with an error.
-
For example:
// Specify an HTTP timeout
const client = new faunadb.Client({
secret: 'YOUR_FAUNADB_SECRET',
timeout: 30,
})
// Specify a query timeout during client instantiation
const client = new faunadb.Client({
queryTimeout: 2000,
secret: 'YOUR_FAUNADB_SECRET',
})
// Specify a query timeout per query
client.query(
q.Paginate(q.Collections()),
{ queryTimeout: 1 }
)
The queryTimeout
passed to .query()
take precedence over any
queryTimeout
specified during client instantiation.
Per-query options
Some options (currently only secret
and queryTimeout
) can be
overridden on a per-query basis:
var createP = client.query(
q.Create(
q.Collection('test'),
{
data: { testField: 'testValue' }
}
),
{ secret: 'YOUR_FAUNADB_SECRET' }
)
var helper = client.paginate(
q.Match(q.Index('test_index'), 'example-term'),
null,
{ secret: 'YOUR_FAUNADB_SECRET', }
)
var data = client.query(
q.Paginate(q.Collections()),
{ queryTimeout: 100 }
)
Code
The JavaScript driver includes no polyfills. Support for Internet
Explorer 11 requires a Promise
polyfill.
Streaming
This section demonstrates how to subscribe to document change events. To learn more, see Streaming.
The following example is an HTML page that uses the JavaScript driver
and plain JavaScript to establish a stream on a document in the Scores
collection, with document id 1
.
To make this example work:
-
Replace
YOUR_FAUNA_SECRET
with the secret that you use to connect to Fauna. -
Host the page in a web server.
-
Open the page in your browser.
<html>
<head>
<style>
span.scores {
font-family: monospace;
white-space: pre;
}
</style>
</head>
<body>
<h1>Scores stream</h1>
<p>
Scores: <span class="scores"></span>
</p>
</body>
<script src="https://cdn.jsdelivr.net/npm/faunadb@latest/dist/faunadb-min.js"></script>
<script type="text/javascript">
var faunadb = window.faunadb
var q = faunadb.query
var client = new faunadb.Client({
secret: 'YOUR_FAUNA_SECRET',
})
var docRef = q.Ref(q.Collection('Scores'), '1')
function report(e) {
console.log(e)
var data = ('action' in e)
? e["document"].data
: e.data
document.body.innerHTML += '<p><span class="scores">' +
JSON.stringify(data) +
'</span></p>'
}
var stream
const startStream = () => {
stream = client.stream.document(docRef)
.on('snapshot', snapshot => {
report(snapshot)
})
.on('version', version => {
report(version)
})
.on('error', error => {
console.log('Error:', error)
stream.close()
setTimeout(startStream, 1000)
})
.start()
}
startStream()
</script>
</html>
If the docRef
example does not exist, the page reports an error to the
browser’s console once per second, and attempts to stream the document
again.
You can use the Web Shell in the Fauna Dashboard, or
fauna-shell
, to run the following
queries to get the collection and document created:
CreateCollection({ name: "Scores" })
Create(Ref(Collection("Scores"), "1"), { data: { scores: [1, 2, 3] }})
If you have the page open in your browser, you should see the contents
of the data
field from that document reported in the web page.
At this point, the stream is setup. Any time that the document is updated or deleted, the stream receives an event reflecting the change and the web page reports the new state. For example:
Update(Ref(Collection("Scores"), "1"), { data: { scores: [5, 2, 3] }})
If you need to stop the stream without closing the browser tab, your
client code can call stream.close()
.
Next steps
-
Driver repository: https://github.com/fauna/faunadb-js
-
Detailed developer documentation for streaming is available within the drive source
-
For more information about the Fauna Query Language, consult our query language reference documentation.
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!