### Setup Application Commands Source: https://docs.faunadb.org/fauna/current/build/sample-apps/streaming CLI commands for cloning, installing, and configuring the Fauna database environment. ```bash git clone https://github.com/fauna-labs/chat-app-streaming ``` ```bash cd chat-app-streaming npm install ``` ```bash fauna login ``` ```bash fauna database create \ --name chat_app \ --database us ``` ```bash fauna schema push \ --database us/chat_app \ --dir ./schema ``` ```bash fauna schema status \ --database us/chat_app ``` ```bash fauna schema commit \ --database us/chat_app ``` ```bash fauna shell \ --database us/chat_app ``` -------------------------------- ### Fauna Export Get Examples Source: https://docs.faunadb.org/cli/llms.txt Examples showing how to retrieve an export, format the output as JSON, and wait for completion. ```cli # Get an export with an ID of '123456789'. fauna export get 123456789 # Get an export as JSON. fauna export get 123456789 \ --json # Wait for the export to complete or fail before exiting. # Waits up to 180 minutes. fauna export get 123456789 \ --wait \ --max-wait 180 ``` -------------------------------- ### Basic Example Source: https://docs.faunadb.org/fauna/current/reference/fql-api/object/fromentries A simple example demonstrating how to convert an array of product entries into an object. ```APIDOC ## Basic Example ### Description This example shows a basic conversion of an array of key-value pairs representing products into an object. ### Method Not Applicable (Function Usage) ### Endpoint Not Applicable (Function Usage) ### Request Example ```javascript // Array containing the name and stock quantity // of various products. let products = [ [ "bananas", 300 ], [ "limes", 200 ], [ "lemons", 500 ] ] // Convert the Array to an Object. Object.fromEntries(products) ``` ### Response Example ```json { "bananas": 300, "limes": 200, "lemons": 500 } ``` ``` -------------------------------- ### Examples Source: https://docs.faunadb.org/fauna/current/build/cli/v4/commands/export/list Illustrative examples of how to use the FaunaDB CLI with various flags. ```APIDOC ## Examples ```bash # List exports in TSV format. fauna export list # List exports in JSON format. fauna export list \ --json # List up to 50 exports. fauna export list \ --max-results 50 # List exports in the 'Pending' or 'Complete' state. fauna export list \ --state Pending Complete ``` ``` -------------------------------- ### Verbose component configuration example Source: https://docs.faunadb.org/fauna/current/build/cli/v4/commands/database/delete Example of passing multiple components to the --verbose-component flag. ```bash --verbose-component argv config ``` -------------------------------- ### Install Fauna .NET/C# Driver Source: https://docs.faunadb.org/fauna/current/build/drivers/dotnet-client Install the Fauna driver using the .NET CLI. ```bash dotnet add package Fauna ``` -------------------------------- ### Install Fauna Go driver Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/go Commands to initialize a Go module and install the Fauna driver dependency. ```bash mkdir app cd app go mod init app go get github.com/fauna/fauna-go/v3 ``` -------------------------------- ### Install Serilog Packages Source: https://docs.faunadb.org/fauna/current/build/drivers/dotnet-client Install the necessary Serilog packages using the dotnet CLI. ```bash dotnet add package Serilog dotnet add package Serilog.Extensions.Logging dotnet add package Serilog.Sinks.Console dotnet add package Serilog.Sinks.File ``` -------------------------------- ### Fauna Configuration File Example Source: https://docs.faunadb.org/fauna/current/build/tools/docker Example YAML configuration for Fauna Dev settings. ```yaml --- auth_root_key: secret cluster_name: fauna storage_data_path: /var/lib/faunadb log_path: /var/log/faunadb shutdown_grace_period_seconds: 0 network_listen_address: 172.17.0.2 network_broadcast_address: 172.17.0.2 network_admin_http_address: 172.17.0.2 network_coordinator_http_address: 172.17.0.2 ``` -------------------------------- ### Example Query Response Source: https://docs.faunadb.org/fauna/current/build/cli/commands/eval An example of the JSON response structure when executing a query like 'Product.all()'. ```json { data: [ { id: "111", coll: Product, ts: Time("2099-07-30T22:55:21.670Z"), name: "cups", description: "Translucent 9 Oz, 100 ct", price: 698, stock: 100, category: Category("123") }, ... ] } ``` -------------------------------- ### Initialize Project and Dependencies Source: https://docs.faunadb.org/fauna/current/build/workshops/aws Clone the starter repository and install required Node.js dependencies. ```bash git clone https://github.com/fauna-labs/faunaproject cd ``` ```bash npm install ``` -------------------------------- ### Example Paginated Results (Intermediate) Source: https://docs.faunadb.org/fauna/current/reference/fql-api/set/pagesize This example shows intermediate results during forward pagination, highlighting the document ID that can be used as a starting point for reverse pagination. ```javascript { data: [ { id: "333", coll: Product, ts: Time("2099-08-16T14:00:59.075Z"), name: "pizza", description: "Frozen Cheese", price: 499, stock: 100, category: Category("456") }, { // Begin reverse pagination from this doc ID. id: "444", coll: Product, ts: Time("2099-08-16T14:00:59.075Z"), name: "avocados", description: "Conventional Hass, 4ct bag", price: 399, stock: 1000, category: Category("789") } ], after: "hdW..." } ``` -------------------------------- ### Initialize Project Directory Source: https://docs.faunadb.org/fauna/current/build/tutorials/schema Create and navigate to a new project directory. ```bash mkdir ecommerce cd ecommerce ``` -------------------------------- ### Configure Client with Convenience Methods Source: https://docs.faunadb.org/clients/go/llms.txt Demonstrates setting various client options using convenience methods, including linearized mode, query timeout, max retries, context, and additional headers. ```go client := fauna.NewClient( "secret", fauna.DefaultTimeouts(), fauna.URL(fauna.EndpointLocal), fauna.HTTPClient(testingClient), fauna.Linearized(true), fauna.QueryTimeout(time.Second*3), fauna.MaxContentionRetries(5), fauna.Context(context.Background()), fauna.AdditionalHeaders(map[string]string{ "foobar": "steve", currentHeader: expectedValue, }), ) assert.NotNil(t, client) ``` -------------------------------- ### Example Get Schema Filenames Response Source: https://docs.faunadb.org/fauna/current/reference/http/reference/core-api A successful response from the get schema filenames endpoint, listing the version and an array of filenames. Each file object contains its `filename`. ```json { "version": 1234567890123456, "files": [ { "filename": "collections.fsl" }, { "filename": "fn/functions.fsl" } ] } ``` -------------------------------- ### Get events after a specific start time Source: https://docs.faunadb.org/fauna/current/build/drivers/py-client Use a start timestamp in microseconds to filter events. The timestamp must be within the collection's history retention period. ```python from fauna import fql from fauna.client import Client, FeedOptions from datetime import datetime, timedelta client = Client() # Calculate timestamp for 10 minutes ago ten_minutes_ago = datetime.now() - timedelta(minutes=10) # Convert to microseconds start_ts = int(ten_minutes_ago.timestamp() * 1_000_000) options = FeedOptions( start_ts=start_ts ) feed = client.feed(fql('Product.all().eventSource()'), options) ``` -------------------------------- ### Run Application Source: https://docs.faunadb.org/fauna/current/build/sample-apps/streaming Command to start the development server. ```bash npm run dev ``` -------------------------------- ### Get current time with Time.now() Source: https://docs.faunadb.org/fauna/current/reference/fql-api/time/now Returns the start time of the current query as a Time object. ```fql Time.now() => Time ``` -------------------------------- ### Database creation examples Source: https://docs.faunadb.org/fauna/current/build/cli/v4/commands/database/create Common usage patterns for creating databases, including top-level, child, and configured databases. ```bash # Create a top-level 'my_db' database # in the 'us' region group. fauna database create \ --name my_db \ --database us # Create a 'child_db' child database # directly under 'us/parent_db'. fauna database create \ --name child_db \ --database us/parent_db # Create a 'child_db' child database directly # under the database scoped to a secret. fauna database create \ --name child_db \ --secret my-secret # Create a database with typechecking enabled. fauna database create \ --name my_db \ --database us \ --typechecked # Create a database with protected mode enabled. fauna database create \ --name my_db \ --database us \ --protected ``` -------------------------------- ### Initialize Client and Parse URLs Source: https://docs.faunadb.org/clients/go/llms.txt Methods for setting up the client instance and resolving API endpoints for queries, streams, and feeds. ```go func (c *Client) parseQueryURL() (*url.URL, error) { if c.queryURL == nil { if queryURL, err := url.Parse(c.url); err != nil { return nil, err } else { c.queryURL = queryURL.JoinPath("query", "1") } } return c.queryURL, nil } ``` ```go func (c *Client) parseStreamURL() (*url.URL, error) { if c.streamURL == nil { if streamURL, err := url.Parse(c.url); err != nil { return nil, err } else { c.streamURL = streamURL.JoinPath("stream", "1") } } return c.streamURL, nil } ``` ```go func (c *Client) parseFeedURL() (*url.URL, error) { if c.feedURL == nil { if feedURL, err := url.Parse(c.url); err != nil { return nil, err } else { c.feedURL = feedURL.JoinPath("feed", "1") } } return c.feedURL, nil } ``` -------------------------------- ### array.foldRight() Example Source: https://docs.faunadb.org/fauna/current/reference/fql-api/array/foldright Demonstrates how to use array.foldRight() to calculate a rolling sum starting with a seed value of 100. ```javascript let iter = [1, 2, 3] iter.foldRight(100, (value, elem) => value + elem) ``` ```plaintext 106 ``` -------------------------------- ### Get events after a specific cursor Source: https://docs.faunadb.org/fauna/current/build/drivers/dotnet-client Use a cursor in FeedOptions to retrieve events starting after a previous page. ```csharp var feedOptions = new FeedOptions(cursor: "gsGabc456"); // Cursor for a previous page var feed = await client.EventFeedAsync(FQL($"Product.all().eventSource()", feedOptions)); ``` -------------------------------- ### Configure Database and Keys via CLI Source: https://docs.faunadb.org/fauna/current/build/workshops/aws Create a new database and generate a server-role key for authentication. ```bash fauna database create \ --name aws_demo \ --database us ``` ```bash fauna query "Key.create({ role: 'server' })" \ --database us/aws_demo ``` -------------------------------- ### Initialize project directory Source: https://docs.faunadb.org/fauna/current/build/tutorials/abac Create a local directory for the project files. ```bash mkdir abac cd abac ``` -------------------------------- ### Install Fauna Go Driver Source: https://docs.faunadb.org/fauna/current/build/drivers/go-client Use the go get command to add the Fauna Go driver to your project. ```bash go get github.com/fauna/fauna-go/v3 ``` -------------------------------- ### Get All Credentials Source: https://docs.faunadb.org/fauna/current/reference/fql-api/credential Retrieves a Set of all credentials in the Credential collection. No specific setup is required beyond having credentials in your database. ```fql Credential.all() ``` -------------------------------- ### Query Fauna in C# Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/dotnet Example implementation for Program.cs to initialize the client and paginate through product data. ```csharp using Fauna; using Fauna.Exceptions; using static Fauna.Query; try { // Initialize the client to connect to Fauna // using the `FAUNA_SECRET` environment variable. var client = new Client(); // Compose a query using an FQL template string. // The query calls the `Product` collection's // `sortedByPriceLowToHigh()` index. It projects the `name`, // `description`, and `price` fields covered by the index. var query = FQL($@" Product.sortedByPriceLowToHigh() { name, description, price } "); // Run the query. var response = client.PaginateAsync>(query); await foreach (var page in response) { foreach (var product in page.Data) { Console.WriteLine(product["name"]); Console.WriteLine(product["description"]); Console.WriteLine(product["price"]); Console.WriteLine("--------"); } } } catch (FaunaException e) { Console.WriteLine(e); } ``` -------------------------------- ### Create Document Example Source: https://docs.faunadb.org/fauna/current/reference/fql/statements Initial document creation for temporal query demonstration. ```FQL Product.create({ id: "9780547928227", name: "lemon", state: "yesterday state" }) ``` ```json { id: "9780547928227", coll: Product, ts: Time("2099-04-10T16:22:32.420Z"), name: "lemon", state: "yesterday state" } ``` -------------------------------- ### Install Fauna Driver using npm Source: https://docs.faunadb.org/fauna/current/build/integration/entra These commands are used within the Azure function app's console to initialize a Node.js project and install the Fauna database driver. This setup is required for the Azure function to interact with FaunaDB. ```bash npm init -y npm install fauna --save ``` -------------------------------- ### Basic distinct() Example Source: https://docs.faunadb.org/fauna/current/reference/fql-api/set/distinct Converts an Array to a Set and then uses `distinct()` to get unique elements. The result is shown in JSON format. ```javascript // `toSet()` converts an Array to a Set. let set = [1, 1, 2, 3, 3].toSet() set.distinct() ``` ```json { data: [ 1, 2, 3 ] } ``` -------------------------------- ### Get events after a specific start time Source: https://docs.faunadb.org/fauna/current/build/drivers/jvm-client Configure FeedOptions with a startTs timestamp to retrieve events occurring after a specific point in time. ```java Query query = fql("Product.all().eventsOn(.price, .stock)"); // Calculate the timestamp for 10 minutes ago in microseconds. long tenMinutesAgo = System.currentTimeMillis() * 1000 - (10 * 60 * 1000 * 1000); FeedOptions options = FeedOptions.builder() .startTs(tenMinutesAgo) .pageSize(10) .build(); // Example 1: Using `feed()` FeedIterator syncIterator = client.feed( query, options, Product.class ); // Example 2: Using `asyncFeed()` CompletableFuture> iteratorFuture = client.asyncFeed( query, options, Product.class ); // Example 3: Using `poll()` QuerySuccess sourceQuery = client.query( query, EventSource.class ); EventSource source = EventSource.fromResponse(sourceQuery.getData()); CompletableFuture> pageFuture = client.poll( source, options, Product.class ); ``` -------------------------------- ### Initialize project directory Source: https://docs.faunadb.org/fauna/current/build/tutorials/auth Create the necessary directory structure for the application schema. ```bash mkdir ecommerce cd ecommerce ``` ```bash mkdir schema ``` -------------------------------- ### String indexOf() - Find Substring Index Source: https://docs.faunadb.org/fauna/current/reference/fql-api/string/indexof Get the index of the first matching substring within a String. An optional start index can be provided. ```FQL indexOf(pattern: String) => Number | Null ``` ```FQL indexOf(pattern: String, start: Number) => Number | Null ``` -------------------------------- ### Get Events After Specific Start Time Source: https://docs.faunadb.org/fauna/current/build/drivers/go-client Use `EventFeedStartTime` to retrieve events that occurred after a specified timestamp (exclusive) when creating an event feed. ```go query, _ := fauna.FQL(`Product.all().eventSource()`, nil) // Calculate timestamp for 10 minutes ago tenMinutesAgo := time.Now().Add(-10 * time.Minute) feed, err := client.FeedFromQuery( query, fauna.EventFeedStartTime(tenMinutesAgo), ) ``` -------------------------------- ### Setup FaunaDB Client and Collection Source: https://docs.faunadb.org/clients/go/llms.txt Initializes the FaunaDB client and sets up a test collection. Ensure the FaunaDB endpoint and secret are configured. ```go t.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal) t.Setenv(fauna.EnvFaunaSecret, "secret") client, clientErr := fauna.NewDefaultClient() require.NoError(t, clientErr) setupQ, _ := fauna.FQL(" Collection.byName('StreamingTest')?.delete() Collection.create({ name: 'StreamingTest' }) ", nil) _, err := client.Query(setupQ) require.NoError(t, err) ``` -------------------------------- ### Configure Event Feed Options Source: https://docs.faunadb.org/clients/go/llms.txt Examples of using FeedOptFn functions to control feed behavior such as start time, cursor position, and page size. ```go tenMinutesAgo := time.Now().Add(-10 * time.Minute) feed := client.FeedFromQuery( fauna.FQL(`Product.all().eventSource()`), fauna.EventFeedStartTime(tenMinutesAgo), ) ``` ```go feed := client.FeedFromQuery( fauna.FQL(`Product.all().eventSource()`), fauna.EventFeedCursor("gsGabc456"), ) ``` ```go feed := client.FeedFromQuery( fauna.FQL(`Product.all().eventSource()`), fauna.EventFeedCursor("gsGabc456"), fauna.EventFeedPageSize(10), ) ``` -------------------------------- ### Initialize Swift Project Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/swift Create a new directory for your Swift application and initialize a new executable Swift package. ```bash mkdir app cd app swift package init --type executable ``` -------------------------------- ### Start Async Fauna Stream from FQL Query Source: https://docs.faunadb.org/clients/jvm/llms.txt Starts a Fauna stream based on an FQL query asynchronously. This involves two requests: one to get the stream token and another to the stream endpoint. Use asyncQuery/asyncStream methods if specific query or stream options are needed. ```java public CompletableFuture> asyncStream(final Query fql, final Class elementClass) { return this.asyncQuery(fql, EventSource.class) .thenApply(queryResponse -> this.stream(queryResponse.getData(), StreamOptions.builder().build(), elementClass)); } ``` -------------------------------- ### Initialize Client with Defaults Source: https://docs.faunadb.org/fauna/current/build/drivers/dotnet-client Initialize the client using environment variables for configuration. ```csharp var client = new Client(); ``` -------------------------------- ### Event Stream Status Event Response Source: https://docs.faunadb.org/fauna/current/learn/cdc Example of a 'status' event received from the Event stream API, indicating the stream has started and providing cursor and statistics. ```json { "type": "status", "txn_ts": 1710968002310000, "cursor": "gsGabc123", "stats": { "read_ops": 8, "storage_bytes_read": 208, "compute_ops": 1, "processing_time_ms": 0, "rate_limits_hit": [] } } ``` -------------------------------- ### Initialize and Configure Fauna Client Source: https://docs.faunadb.org/clients/go/llms.txt Demonstrates various ways to instantiate a Fauna client, including default settings, environment variable usage, and custom HTTP client injection. ```go func TestNewClient(t *testing.T) { t.Run("default client", func(t *testing.T) { t.Setenv(fauna.EnvFaunaSecret, "secret") _, clientErr := fauna.NewDefaultClient() assert.NoError(t, clientErr) }) t.Run("new client respects env var", func(t *testing.T) { t.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal) client := fauna.NewClient("secret", fauna.DefaultTimeouts()) assert.NotNil(t, client) assert.Equal(t, client.String(), fauna.EndpointLocal) }) t.Run("stringify", func(t *testing.T) { client := fauna.NewClient("secret", fauna.DefaultTimeouts(), fauna.URL(fauna.EndpointLocal)) assert.Equal(t, client.String(), fauna.EndpointLocal, "client toString should be equal to the endpoint to ensure we don't expose secrets") }) t.Run("missing secret", func(t *testing.T) { _, clientErr := fauna.NewDefaultClient() assert.Error(t, clientErr, "should have failed due to missing secret") }) t.Run("has transaction time", func(t *testing.T) { t.Setenv(fauna.EnvFaunaSecret, "secret") t.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal) client, clientErr := fauna.NewDefaultClient() if !assert.NoError(t, clientErr) { return } before := client.GetLastTxnTime() if !assert.Zero(t, before) { return } q, _ := fauna.FQL(`Math.abs(-5.123e3)`, nil) if _, queryErr := client.Query(q); !assert.NoError(t, queryErr) { return } first := client.GetLastTxnTime() assert.NotZero(t, first) second := client.GetLastTxnTime() assert.Equal(t, first, second) assert.NotEqual(t, before, second) }) t.Run("custom HTTP client", func(t *testing.T) { client := fauna.NewClient( "secret", fauna.DefaultTimeouts(), fauna.URL(fauna.EndpointLocal), fauna.HTTPClient(http.DefaultClient), ) q, _ := fauna.FQL(`Math.abs(-5.123e3)`, nil) _, queryErr := client.Query(q) assert.NoError(t, queryErr) }) } ``` -------------------------------- ### Get Keys up to a Specific ID in FaunaDB Source: https://docs.faunadb.org/fauna/current/reference/fql-api/key/all Retrieves a Set of Key documents up to and including the specified `to` Key document. Omit the `from` parameter to start from the beginning of the keys. ```javascript Key.all({ to: Key.byId("222") }) ``` -------------------------------- ### Get Event Source and Stream Options Source: https://docs.faunadb.org/clients/jvm/llms.txt Obtain an event source from a query and set stream options, including a start timestamp. This is useful for subscribing to changes in a Set. ```java Query query = fql("Product.all().eventSource() { name, stock }"); QuerySuccess tokenResponse = client.query(query, EventSource.class); EventSource eventSource = EventSource.fromResponse(querySuccess.getData()); // Calculate the timestamp for 10 minutes ago in microseconds. long tenMinutesAgo = System.currentTimeMillis() * 1000 - (10 * 60 * 1000 * 1000); StreamOptions streamOptions = StreamOptions.builder().startTimestamp(tenMinutesAgo).build(); ``` -------------------------------- ### Run the .NET application Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/dotnet Execute the console application to fetch and print the product data. ```bash dotnet run ``` -------------------------------- ### FQL Array slice() Method Source: https://docs.faunadb.org/fauna/current/reference/fql-api/array/slice Use slice() to get a subset of an Array's elements. It copies elements from a start index (inclusive) up to an end index (exclusive). ```fql array.slice(from: Number) => Array array.slice(from: Number, until: Number) => Array ``` -------------------------------- ### Initialize Schema Directory Source: https://docs.faunadb.org/fauna/current/build/workshops/cloudflare Create a local directory for schema files and navigate into it. ```bash mkdir schema && cd schema ``` -------------------------------- ### Heredoc String Example Source: https://docs.faunadb.org/fauna/current/reference/fql/types Illustrates the use of heredoc strings for multi-line text. These strings are delimited by tokens starting with '<<' and preserve line breaks. Leading whitespace on each line is removed. ```fql <<+STR A multiline string STR ``` -------------------------------- ### Get First Page of Products Source: https://docs.faunadb.org/fauna/current/learn/query/pagination Retrieve the first page of products, starting from a price of 0. The query fetches one extra item to indicate the availability of a next page. ```fql // Gets the first page of products, // starting with a price of `0`. Product.inOrderOfPrice({ from: [0] })! .take(5 + 1) // PAGE_SIZE + 1 .toArray() { id, name, price } ``` -------------------------------- ### Run the application Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/nodejs Executes the Node.js script to display product data. ```bash node app.mjs ``` -------------------------------- ### Configure stream options in Go Source: https://docs.faunadb.org/clients/go/llms.txt Demonstrates using StreamStartTime and EventCursor to control stream initialization and resumption. ```go streamQuery, _ := fauna.FQL(`Product.all().eventSource()`, nil) tenMinutesAgo := time.Now().Add(-10 * time.Minute) client.StreamFromQuery(streamQuery, nil, fauna.StreamStartTime(tenMinutesAgo)) ``` ```go streamQuery, _ := fauna.FQL(`Product.all().toStream()`, nil) client.StreamFromQuery(streamQuery, nil, fauna.EventCursor("abc2345==")) ``` -------------------------------- ### String.indexOfRegex() - Find substring index with regex Source: https://docs.faunadb.org/fauna/current/reference/fql-api/string/indexofregex Get the index of the first substring matching a provided regular expression within a String. This method can optionally take a starting index for the search. ```FQL indexOfRegex(regex: String) => Number | Null ``` ```FQL indexOfRegex(regex: String, start: Number) => Number | Null ``` -------------------------------- ### Initialize Rust project Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/rust Creates a new directory and initializes a standard Rust project structure. ```bash mkdir app cd app cargo init ``` -------------------------------- ### Get and Subscribe to Event Source with StreamOptions Source: https://docs.faunadb.org/fauna/current/build/drivers/jvm-client Obtain an event source from a query and subscribe to its stream with specific options, such as a start timestamp. Ensure the EventSource is correctly initialized from the query response. ```java Query query = fql("Product.all().eventSource() { name, stock }"); QuerySuccess tokenResponse = client.query(query, EventSource.class); EventSource eventSource = EventSource.fromResponse(querySuccess.getData()); // Calculate the timestamp for 10 minutes ago in microseconds. long tenMinutesAgo = System.currentTimeMillis() * 1000 - (10 * 60 * 1000 * 1000); StreamOptions streamOptions = StreamOptions.builder().startTimestamp(tenMinutesAgo).build(); // Example 1: Using `stream()` FaunaStream stream = client.stream(eventSource, streamOptions, Product.class); // Example 2: Using `asyncStream()` CompletableFuture> futureStream = client.asyncStream(source, streamOptions, Product.class); ``` -------------------------------- ### Initialize Node.js Project and Install Fauna Driver Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/aws-lambda Use these commands to create a new Node.js project directory, initialize it with npm, and install the Fauna JavaScript driver. ```bash mkdir myFaunaLambda cd myFaunaLambda npm init -y npm install fauna ``` -------------------------------- ### Get Events After a Specific Start Timestamp Source: https://docs.faunadb.org/clients/python/llms.txt Configure an event feed to retrieve events that occurred after a specific timestamp. The `start_ts` is provided in microseconds since the Unix epoch within the FeedOptions. ```python from fauna import fql from fauna.client import Client, FeedOptions from datetime import datetime, timedelta client = Client() # Calculate timestamp for 10 minutes ago ten_minutes_ago = datetime.now() - timedelta(minutes=10) ``` -------------------------------- ### Start a Stream Client Source: https://docs.faunadb.org/clients/js/llms.txt Initiates a stream to listen for events from a FaunaDB collection. Handles 'update', 'add', and 'remove' event types. Requires setup of event handlers for data and errors. ```javascript const stream = client.stream(fql`MyCollection.all().eventSource()`) stream.start( function onEvent(event) { switch (event.type) { case "update": case "add": case "remove": console.log("Stream update:", event); // ... break; } }, function onError(error) { // An error will be handled here if Fauna returns a terminal, "error" event, or // if Fauna returns a non-200 response when trying to connect, or // if the max number of retries on network errors is reached. // ... handle fatal error } ); ``` -------------------------------- ### Example First Page Results Source: https://docs.faunadb.org/fauna/current/learn/query/pagination Sample JSON output for the first page of product results, containing six items to indicate pagination availability. ```json [ { "id": "555", "name": "single lime", "price": 35 }, { "id": "888", "name": "cilantro", "price": 149 }, { "id": "777", "name": "limes", "price": 299 }, { "id": "666", "name": "organic limes", "price": 349 }, { "id": "444", "name": "avocados", "price": 399 }, { "id": "333", "name": "pizza", "price": 499 } ] ``` -------------------------------- ### Get Keys within a Range in FaunaDB Source: https://docs.faunadb.org/fauna/current/reference/fql-api/key/all Retrieves a Set of Key documents within a specified range, inclusive of the `from` and `to` Key documents. Use `Key.byId()` to specify the start and end points of the range. ```javascript Key.all({ from: Key.byId("111"), to: Key.byId("222") }) ``` -------------------------------- ### Request Initial Page and Event Source Source: https://docs.faunadb.org/fauna/current/build/drivers/go-client Initialize a client and query for an initial page of results along with an event source from a set. ```go client := fauna.NewClient( "FAUNA_SECRET", fauna.DefaultTimeouts(), ) query, _ := fauna.FQL(` let set = Product.all() { initialPage: set.pageSize(10), eventSource: set.eventSource() } `, nil) res, err := client.Query(query) if err != nil { log.Fatalf("Failed to query: %v", err) } var result struct { InitialPage fauna.Page `fauna:"initialPage"` EventSource fauna.EventSource `fauna:"eventSource"` } if err := res.Unmarshal(&result); err != nil { log.Fatalf("Failed to unmarshal results: %v", err) } feed, err := client.Feed(result.EventSource) if err != nil { log.Fatalf("Failed to create feed: %v", err) } ``` -------------------------------- ### Get Events After a Specific Start Timestamp Source: https://docs.faunadb.org/fauna/current/build/drivers/js-client Configure the event feed to retrieve events that occurred after a specific timestamp (exclusive) by providing the `start_ts` option. The timestamp must be in microseconds since the Unix epoch. ```javascript // Calculate timestamp for 10 minutes ago const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000); // Convert to microseconds const startTs = Math.floor(tenMinutesAgo.getTime() / 1000) * 1000000; const options = { start_ts: startTs }; const feed = client.feed(fql`Product.all().eventSource()`, options); ``` -------------------------------- ### Create basic Fauna Go application Source: https://docs.faunadb.org/fauna/current/get-started/quick-start/go Initializes a Fauna client and executes a paginated FQL query to fetch product data. ```go package main import ( "fmt" "github.com/fauna/fauna-go/v3" ) func main() { // Initialize the client to connect to Fauna // using the `FAUNA_SECRET` environment variable. client, clientErr := fauna.NewDefaultClient() if clientErr != nil { panic(clientErr) } // Compose a query using an FQL template string. // The query calls the `Product` collection's // `sortedByPriceLowToHigh()` index. It projects the `name`, // `description`, and `price` fields covered by the index. query, _ := fauna.FQL(` Product.sortedByPriceLowToHigh() { name, description, price } `, nil) // Run the query. paginator := client.Paginate(query) // Iterate through the results. for { page, _ := paginator.Next() var pageItems []any page.Unmarshal(&pageItems) for _, item := range pageItems { jsonData, _ := json.Marshal(item) fmt.Println(string(jsonData)) } if !paginator.HasNext() { break } } } ``` -------------------------------- ### Take first N elements from a Set Source: https://docs.faunadb.org/fauna/current/reference/fql-api/set/take Use this method to get the first N documents from a Set. The original Set remains unchanged. Ensure the Set is already defined, for example, by calling .all() on a collection. ```javascript Product.all().take(2) ``` -------------------------------- ### Create a top-level database Source: https://docs.faunadb.org/cli/llms.txt Example of creating a database in the 'us' region group. ```cli # Create a top-level 'my_db' database # in the 'us' region group. fauna database create \ --name my_db \ --database us ``` -------------------------------- ### Get Next Page of Products Source: https://docs.faunadb.org/fauna/current/learn/query/pagination Retrieve the next page of products by starting the ranged search from the price and ID of the last item from the previous results. Fetches one extra item to check for subsequent pages. ```fql // Gets the next page of products, // starting with the `price` (499) and document `id` of last item // from the previous results. Product.inOrderOfPrice({ from: [499, "333"] })! .take(5 + 1) // PAGE_SIZE + 1 .toArray() { id, name, price } ``` -------------------------------- ### Execute Basic FQL Query Source: https://docs.faunadb.org/fauna/current/build/drivers/go-client Initialize a client and execute a query using an FQL string template. ```go package main import ( "fmt" "github.com/fauna/fauna-go/v3" ) func main() { // Initialize the client to connect to Fauna client := fauna.NewClient( "FAUNA_SECRET", fauna.DefaultTimeouts(), ) // Compose a query query, _ := fauna.FQL(` Product.sortedByPriceLowToHigh() { name, description, price } `, nil) res, err := client.Query(query) if err != nil { panic(err) } jsonData, _ := json.Marshal(res.Data) fmt.Println(string(jsonData)) } ``` -------------------------------- ### Example Query Result Source: https://docs.faunadb.org/fauna/current/build/tutorials/schema Sample output from a Product collection query. ```JSON { data: [ { id: "400414078704549921", coll: Product, ts: Time("2099-06-11T16:31:12.790Z"), name: "pinata", description: "Original Classic Donkey Pinata", price: 2499, stock: 40 }, ... ] } ``` -------------------------------- ### Get Query Results Alongside Event Stream (JavaScript) Source: https://docs.faunadb.org/fauna/current/learn/cdc Pass an event source token to `stream()` to receive query results concurrently with real-time events. This example fetches products and their corresponding event source. ```javascript import { Client, fql } from "fauna"; const client = new Client(); const query = fql` let products = Product.where( .type == 'book' && .price < 100_00) { products: products, eventSource: products.eventSource() }`; const response = await client.query(query); const { products, eventSource } = response.data; for await (const product of client.paginate(products)) { console.log(product); } const stream = client.stream(eventSource); try { for await (const event of stream) { switch (event.type) { case "add": // Do something on add console.log(event.data); break; case "update": // Do something on update console.log(event.data); break; case "remove": // Do something on remove console.log(event.data); break; } } } catch (error) { console.log(error); } ```