fauna
Version:
A driver to query Fauna databases in browsers, Node.js, and other Javascript runtimes
281 lines (280 loc) • 11.3 kB
TypeScript
import { type ClientConfiguration, type FeedClientConfiguration, type StreamClientConfiguration } from "./client-configuration";
import { type HTTPClient } from "./http-client";
import { Query } from "./query-builder";
import { FeedPage, Page, SetIterator, type EmbeddedSet, type EventSource } from "./values";
import { type QueryOptions, type QuerySuccess, type QueryValue, type StreamEventData, type StreamEventStatus } from "./wire-protocol";
/**
* Client for calling Fauna.
*/
export declare class Client {
#private;
/**
* Constructs a new {@link Client}.
* @param clientConfiguration - the {@link ClientConfiguration} to apply. Defaults to recommended ClientConfiguraiton.
* @param httpClient - The underlying {@link HTTPClient} that will execute the actual HTTP calls. Defaults to recommended HTTPClient.
* @example
* ```typescript
* const myClient = new Client(
* {
* endpoint: endpoints.cloud,
* secret: "foo",
* query_timeout_ms: 60_000,
* }
* );
* ```
*/
constructor(clientConfiguration?: ClientConfiguration, httpClient?: HTTPClient);
/**
* @returns the last transaction time seen by this client, or undefined if this client has not seen a transaction time.
*/
get lastTxnTs(): number | undefined;
/**
* Sets the last transaction time of this client.
* @param ts - the last transaction timestamp to set, as microseconds since
* the epoch. If `ts` is less than the existing `#lastTxnTs` value or is
* undefined , then no change is made.
*/
set lastTxnTs(ts: number | undefined);
/**
* Return the {@link ClientConfiguration} of this client.
*/
get clientConfiguration(): ClientConfiguration;
/**
* Closes the underlying HTTP client. Subsequent query or close calls
* will fail.
*/
close(): void;
/**
* Creates an iterator to yield pages of data. If additional pages exist, the
* iterator will lazily fetch addition pages on each iteration. Pages will
* be retried in the event of a ThrottlingError up to the client's configured
* max_attempts, inclusive of the initial call.
*
* @typeParam T - The expected type of the items returned from Fauna on each
* iteration. T can be inferred if the provided query used a type parameter.
* @param iterable - a {@link Query} or an existing fauna Set ({@link Page} or
* {@link EmbeddedSet})
* @param options - a {@link QueryOptions} to apply to the queries. Optional.
* @returns A {@link SetIterator} that lazily fetches new pages of data on
* each iteration
*
* @example
* ```javascript
* const userIterator = await client.paginate(fql`
* Users.all()
* `);
*
* for await (const users of userIterator) {
* for (const user of users) {
* // do something with each user
* }
* }
* ```
*
* @example
* The {@link SetIterator.flatten} method can be used so the iterator yields
* items directly. Each item is fetched asynchronously and hides when
* additional pages are fetched.
*
* ```javascript
* const userIterator = await client.paginate(fql`
* Users.all()
* `);
*
* for await (const user of userIterator.flatten()) {
* // do something with each user
* }
* ```
*/
paginate<T extends QueryValue>(iterable: Page<T> | EmbeddedSet | Query<T | Page<T>>, options?: QueryOptions): SetIterator<T>;
/**
* Queries Fauna. Queries will be retried in the event of a ThrottlingError up to the client's configured
* max_attempts, inclusive of the initial call.
*
* @typeParam T - The expected type of the response from Fauna. T can be inferred if the
* provided query used a type parameter.
* @param query - a {@link Query} to execute in Fauna.
* Note, you can embed header fields in this object; if you do that there's no need to
* pass the headers parameter.
* @param options - optional {@link QueryOptions} to apply on top of the request input.
* Values in this headers parameter take precedence over the same values in the {@link ClientConfiguration}.
* @returns Promise<{@link QuerySuccess}>.
*
* @throws {@link ServiceError} Fauna emitted an error. The ServiceError will be
* one of ServiceError's child classes if the error can be further categorized,
* or a concrete ServiceError if it cannot.
* You can use either the type, or the underlying httpStatus + code to determine
* the root cause.
* @throws {@link ProtocolError} the client a HTTP error not sent by Fauna.
* @throws {@link NetworkError} the client encountered a network issue
* connecting to Fauna.
* @throws A {@link ClientError} the client fails to submit the request
* @throws {@link ClientClosedError} if a query is issued after the client is closed.
* due to an internal error.
*/
query<T extends QueryValue>(query: Query<T>, options?: QueryOptions): Promise<QuerySuccess<T>>;
/**
* Initialize a streaming request to Fauna
* @typeParam T - The expected type of the response from Fauna. T can be inferred
* if the provided query used a type parameter.
* @param tokenOrQuery - A string-encoded token for an {@link EventSource}, or a {@link Query}
* @returns A {@link StreamClient} that which can be used to listen to a stream
* of events
*
* @example
* ```javascript
* const stream = client.stream(fql`MyCollection.all().eventSource()`)
*
* try {
* for await (const event of stream) {
* switch (event.type) {
* case "update":
* case "add":
* case "remove":
* console.log("Stream update:", event);
* // ...
* break;
* }
* }
* } catch (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
* ```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
* }
* );
* ```
*/
stream<T extends QueryValue>(tokenOrQuery: EventSource | Query<EventSource>, options?: Partial<StreamClientConfiguration>): StreamClient<T>;
/**
* Initialize a event feed in Fauna and returns an asynchronous iterator of
* feed events.
* @typeParam T - The expected type of the response from Fauna. T can be inferred
* if the provided query used a type parameter.
* @param tokenOrQuery - A string-encoded token for an {@link EventSource}, or a {@link Query}
* @returns A {@link FeedClient} that which can be used to listen to a feed
* of events
*
* @example
* ```javascript
* const feed = client.feed(fql`MyCollection.all().eventSource()`)
*
* try {
* for await (const page of feed) {
* for (const event of page.events) {
* // ... handle event
* }
* }
* } catch (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
* The {@link FeedClient.flatten} method can be used so the iterator yields
* events directly. Each event is fetched asynchronously and hides when
* additional pages are fetched.
*
* ```javascript
* const feed = client.feed(fql`MyCollection.all().eventSource()`)
*
* for await (const user of feed.flatten()) {
* // do something with each event
* }
* ```
*/
feed<T extends QueryValue>(tokenOrQuery: EventSource | Query<EventSource>, options?: Partial<FeedClientConfiguration>): FeedClient<T>;
}
/**
* A class to listen to Fauna streams.
*/
export declare class StreamClient<T extends QueryValue = any> {
#private;
/** Whether or not this stream has been closed */
closed: boolean;
/**
*
* @param token - A lambda that returns a promise for a {@link EventSource}
* @param clientConfiguration - The {@link ClientConfiguration} to apply
* @example
* ```typescript
* const streamClient = client.stream(eventSource);
* ```
*/
constructor(token: EventSource | (() => Promise<EventSource>), clientConfiguration: StreamClientConfiguration);
/**
* A synchronous method to start listening to the stream and handle events
* using callbacks.
* @param onEvent - A callback function to handle each event
* @param onError - An Optional callback function to handle errors. If none is
* provided, error will not be handled, and the stream will simply end.
*/
start(onEvent: (event: StreamEventData<T> | StreamEventStatus) => void, onError?: (error: Error) => void): void;
[Symbol.asyncIterator](): AsyncGenerator<StreamEventData<T> | StreamEventStatus>;
close(): void;
get last_ts(): number | undefined;
}
/**
* A class to iterate through to a Fauna event feed.
*/
export declare class FeedClient<T extends QueryValue = any> {
#private;
/**
*
* @param token - A lambda that returns a promise for a {@link EventSource}
* @param clientConfiguration - The {@link FeedClientConfiguration} to apply
* @example
* ```typescript
* const feed = client.feed(eventSource);
* ```
*/
constructor(token: EventSource | (() => Promise<EventSource>), clientConfiguration: FeedClientConfiguration);
[Symbol.asyncIterator](): AsyncGenerator<FeedPage<T>>;
/**
* Fetches the next page of the event feed. If there are no more pages to
* fetch, this method will throw a {@link ClientError}.
*/
nextPage(): Promise<FeedPage<T>>;
/**
* Returns an async generator that yields the events of the event feed
* directly.
*
* @example
* ```javascript
* const feed = client.feed(fql`MyCollection.all().eventSource()`)
*
* for await (const user of feed.flatten()) {
* // do something with each event
* }
* ```
*/
flatten(): AsyncGenerator<StreamEventData<T>>;
}