UNPKG

arangojs

Version:

The official ArangoDB JavaScript driver.

518 lines 16.6 kB
/// <reference types="node" resolution-mode="require"/> /// <reference types="node" resolution-mode="require"/> /** * ```ts * import type { ArangoApiResponse } from "arangojs/connection"; * ``` * * The "connection" module provides connection related types for TypeScript. * * @packageDocumentation */ import * as administration from "./administration.js"; import * as configuration from "./configuration.js"; import * as databases from "./databases.js"; import * as errors from "./errors.js"; import { LinkedList } from "./lib/x3-linkedlist.js"; /** * @internal */ type Host = { /** * @internal * * Perform a fetch request against this host. * * @param pathname - URL path, relative to the server URL. * @param options - Options for this fetch request. */ fetch: (options: Omit<RequestOptions, "maxRetries" | "retryOnConflict" | "allowDirtyRead" | "hostUrl" | "expectBinary" | "isBinary">) => Promise<globalThis.Response & { request: globalThis.Request; }>; /** * @internal * * Close the pending request, if any. */ close: () => void; }; /** * Returns the status message for the given response's status code or the * status text of the response. */ export declare function getStatusMessage(response: ProcessedResponse): string; /** * Generic properties shared by all ArangoDB HTTP API responses. */ export type ArangoResponseMetadata = { /** * Indicates that the request was successful. */ error: false; /** * Response status code, typically `200`. */ code: number; }; /** * Extends the given base type `T` with the generic HTTP API response properties. */ export type ArangoApiResponse<T> = T & ArangoResponseMetadata; /** * Indicates whether the given value represents an ArangoDB error response. */ export declare function isArangoErrorResponse(body: unknown): body is ArangoErrorResponse; /** * Interface representing an ArangoDB error response. */ export type ArangoErrorResponse = { /** * Indicates that the request resulted in an error. */ error: true; /** * Intended response status code as provided in the response body. */ code?: number; /** * Error message as provided in the response body. */ errorMessage: string; /** * ArangoDB error code as provided in the response body. * * See the [ArangoDB error documentation](https://docs.arangodb.com/stable/develop/error-codes-and-meanings/) * for more information. */ errorNum: number; }; /** * Processed response object. */ export interface ProcessedResponse<T = any> extends globalThis.Response { /** * @internal * * Identifier of the ArangoDB host that served this request. */ arangojsHostUrl?: string; /** * Fetch request object. */ request: globalThis.Request; /** * Parsed response body. */ parsedBody?: T; } /** * Options available for requests made with the Fetch API. */ export type CommonFetchOptions = { /** * Headers object containing any additional headers to send with the request. * * Note that the `Authorization` header will be overridden if the `auth` * configuration option is set. */ headers?: string[][] | Record<string, string | ReadonlyArray<string>> | Headers; /** * Controls whether the socket should be reused for subsequent requests. * * Default: `false` */ keepalive?: boolean; /** * Controls what to do when the response status code is a redirect. * * - `"error"`: Abort with a network error. * - `"follow"`: Automatically follow redirects. * - `"manual"`: Abort with an `HttpError`. * * Default: `"follow"` */ redirect?: "error" | "follow" | "manual"; /** * Value to use for the `Referer` header. * * If set to `"about:client"`, the default value for the context in which the * request is made will be used. * * Default: `"about:client"` */ referrer?: string; /** * (Browser only.) Controls the Attribution Reporting API specific behavior. * * See the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) * for more information on the available options. */ attributionReporting?: any; /** * (Browser only.) Cache mode to use for the request. * * See [the Fetch API specification](https://fetch.spec.whatwg.org/#request-class) * or the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) * for more information on the available options. */ cache?: string; /** * (Browser only.) Controls sending of credentials and cookies. * * - `"omit"`: Never send cookies. * - `"include"`: Always send cookies. * - `"same-origin"`: Only send cookies if the request is to the same origin. * * Default: `"same-origin"` */ credentials?: "omit" | "include" | "same-origin"; /** * (Node.js only.) Undici `Dispatcher` instance to use for the request. * * Defaults to the global dispatcher. */ dispatcher?: any; /** * (Browser only.) Sets cross-origin behavior for the request. * * See [the Fetch API specification](https://fetch.spec.whatwg.org/#request-class) * or the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) * for more information on the available options. * * Default: `"cors"` */ mode?: string; /** * (Browser only.) Request priority relative to other requests of the same type. * * See [the Fetch API specification](https://fetch.spec.whatwg.org/#request-class) * or the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) * for more information on the available options. * * Default: `"auto"` */ priority?: "low" | "high" | "auto"; /** * (Browser only.) Policy to use for the `Referer` header, equivalent to the * semantics of the `Referrer-Policy` header. * * See [the Fetch API specification](https://fetch.spec.whatwg.org/#request-class) * or the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) * for more information on the available options. */ referrerPolicy?: string; }; /** * Fetch-specific options for performing a request with arangojs. */ export type FetchOptions = CommonFetchOptions & { /** * Subresource integrity value to use for the request, formatted as * `<hash-algorithm>-<hash-source>`. */ integrity?: `${string}-${string}`; }; /** * Options that can be shared globally for all requests made with arangojs. */ export type CommonRequestOptions = { /** * Determines the behavior when a request fails because the underlying * connection to the server could not be opened * (e.g. [`ECONNREFUSED` in Node.js](https://nodejs.org/api/errors.html#errors_common_system_errors)): * * - `false`: the request fails immediately. * * - `0`: the request is retried until a server can be reached but only a * total number of times matching the number of known servers (including * the initial failed request). * * - any other number: the request is retried until a server can be reached * or the request has been retried a total of `maxRetries` number of times * (not including the initial failed request). * * When working with a single server, the retries (if any) will be made to * the same server. * * This setting currently has no effect when using arangojs in a browser. * * **Note**: Requests bound to a specific server (e.g. fetching query results) * will never be retried automatically and ignore this setting. * * **Note**: To set the number of retries when a write-write conflict is * encountered, see `retryOnConflict` instead. * * Default: `0` */ maxRetries?: false | number; /** * If set to a positive number, requests will automatically be retried at * most this many times if they result in a write-write conflict. * * Default: `0` */ retryOnConflict?: number; /** * Time in milliseconds after which arangojs will abort the request if the * socket has not already timed out. */ timeout?: number; /** * Whether ArangoDB is allowed to perform a dirty read to respond to the * request. If set to `true`, the response may reflect a dirty state from * a non-authoritative server. * * Default: `false` */ allowDirtyRead?: boolean; /** * Callback that will be invoked with the finished request object before it * is finalized. In the browser the request may already have been sent. * * @param req - Request object or XHR instance used for this request. */ beforeRequest?: (req: globalThis.Request) => void | Promise<void>; /** * Callback that will be invoked when the server response has been received * and processed or when the request has been failed without a response. * * The originating request will be available as the `request` property * on either the error or response object. * * @param err - Error encountered when handling this request or `null`. * @param res - Response object for this request, if no error occurred. */ afterResponse?: (err: errors.NetworkError | null, res?: globalThis.Response & { request: globalThis.Request; }) => void | Promise<void>; }; /** * Options for performing a request with arangojs. */ export type RequestOptions = CommonRequestOptions & { /** * @internal * * Identifier of a specific ArangoDB host to use when more than one is known. */ hostUrl?: string; /** * HTTP method to use in order to perform the request. * * Default: `"GET"` */ method?: string; /** * URL path, relative to the server domain. */ pathname?: string; /** * URL parameters to pass as part of the query string. */ search?: URLSearchParams | Record<string, any>; /** * Headers object containing any additional headers to send with the request. * * Note that the `Authorization` header will be overridden if the `auth` * configuration option is set. */ headers?: string[][] | Record<string, string | ReadonlyArray<string>> | Headers; /** * Request body data. */ body?: any; /** * Additional options to pass to the `fetch` function. */ fetchOptions?: Omit<FetchOptions, "headers">; /** * If set to `true`, the request body will not be converted to JSON and * instead passed as-is. */ isBinary?: boolean; /** * If set to `true`, the response body will not be interpreted as JSON and * instead passed as-is. */ expectBinary?: boolean; }; /** * @internal */ type Task<T = any> = { stack?: () => string; resolve: (result: T) => void; reject: (error: unknown) => void; transform?: (res: ProcessedResponse<any>) => T; retries: number; conflicts: number; options: RequestOptions; }; /** * Indicates whether the given value represents a {@link Connection}. * * @param connection - A value that might be a connection. * * @internal */ export declare function isArangoConnection(connection: any): connection is Connection; /** * Represents a connection pool shared by one or more databases. * * @internal */ export declare class Connection { protected _activeTasks: number; protected _arangoVersion: number; protected _loadBalancingStrategy: configuration.LoadBalancingStrategy; protected _taskPoolSize: number; protected _commonRequestOptions: CommonRequestOptions; protected _commonFetchOptions: CommonFetchOptions & { headers: Headers; }; protected _queue: LinkedList<Task<any>>; protected _databases: Map<string, databases.Database>; protected _hosts: Host[]; protected _hostUrls: string[]; protected _activeHostUrl: string; protected _activeDirtyHostUrl: string; protected _transactionId: string | null; protected _onError?: (err: Error) => void | Promise<void>; protected _precaptureStackTraces: boolean; protected _queueTimes: LinkedList<[number, number]>; protected _responseQueueTimeSamples: number; /** * @internal * * Creates a new `Connection` instance. * * @param config - An object with configuration options. * */ constructor(config?: Omit<configuration.ConfigOptions, "databaseName">); /** * @internal * * Indicates that this object represents an ArangoDB connection. */ get isArangoConnection(): true; get queueTime(): administration.QueueTimeMetrics; protected _runQueue(): Promise<void>; setBearerAuth(auth: configuration.BearerAuthCredentials): void; setBasicAuth(auth: configuration.BasicAuthCredentials): void; setResponseQueueTimeSamples(responseQueueTimeSamples: number): void; /** * @internal * * Fetches a {@link databases.Database} instance for the given database name from the * internal cache, if available. * * @param databaseName - Name of the database. */ database(databaseName: string): databases.Database | undefined; /** * @internal * * Adds a {@link databases.Database} instance for the given database name to the * internal cache. * * @param databaseName - Name of the database. * @param database - Database instance to add to the cache. */ database(databaseName: string, database: databases.Database): databases.Database; /** * @internal * * Clears any {@link databases.Database} instance stored for the given database name * from the internal cache, if present. * * @param databaseName - Name of the database. * @param database - Must be `null`. */ database(databaseName: string, database: null): undefined; /** * @internal * * Replaces the host list with the given URLs. * * See {@link Connection#acquireHostList}. * * @param urls - URLs to use as host list. */ setHostList(urls: string[]): void; /** * @internal * * Adds the given URL or URLs to the host list. * * See {@link Connection#acquireHostList}. * * @param urls - URL or URLs to add. */ addToHostList(urls: string | string[]): string[]; /** * @internal * * Sets the connection's active `transactionId`. * * While set, all requests will use this ID, ensuring the requests are executed * within the transaction if possible. Setting the ID manually may cause * unexpected behavior. * * See also {@link Connection#clearTransactionId}. * * @param transactionId - ID of the active transaction. */ setTransactionId(transactionId: string): void; /** * @internal * * Clears the connection's active `transactionId`. */ clearTransactionId(): void; /** * @internal * * Sets the header `headerName` with the given `value` or clears the header if * `value` is `null`. * * @param headerName - Name of the header to set. * @param value - Value of the header. */ setHeader(headerName: string, value: string | null): void; /** * @internal * * Closes all open connections. * * See {@link databases.Database#close}. */ close(): void; /** * @internal * * Waits for propagation. * * See {@link databases.Database#waitForPropagation}. * * @param request - Request to perform against each coordinator. * @param timeout - Maximum number of milliseconds to wait for propagation. */ waitForPropagation(request: RequestOptions, timeout?: number): Promise<void>; /** * @internal * * Performs a request using the arangojs connection pool. */ request<T = globalThis.Response & { request: globalThis.Request; parsedBody?: any; }>(requestOptions: RequestOptions & { isBinary?: boolean; }, transform?: (res: globalThis.Response & { request: globalThis.Request; parsedBody?: any; }) => T): Promise<T>; } export {}; //# sourceMappingURL=connection.d.ts.map