Skip to content

Connecting

Importing

import { Surreal } from "@tai-kun/surrealdb";

.constructor()

new Surreal();

Arguments

None.

Return Value

When called via new, Surreal returns its instance.

.connect() instance method

Connects to the SurrealDB endpoint. This method executes asynchronously, but will not execute concurrently with other .connect() or .close() calls within the same instance.

connect(
endpoint: string | URL,
options?: ClientConnectOptions,
): Promise<void>;

Arguments

endpoint

Specifies the SurrealDB endpoint as a URL. If the URL path does not end with /rpc, it will be automatically appended. Therefore, passing http://localhost:8000 will connect to http://localhost:8000/rpc.

options

Connection options.

signal?: AbortSignal
An abort signal to interrupt the connection. By default, an abort signal with a 15-second timeout is set.

Return Value

Returns a Promise object that resolves to undefined.

Example

The following example connects to SurrealDB using the WebSocket protocol:

import { Surreal } from "@tai-kun/surrealdb";
const db = new Surreal();
await db.connect("ws://localhost:8000");

Connecting to a different endpoint without disconnecting using .close() is not allowed. The connection to the previously established endpoint will be maintained:

import { Surreal } from "@tai-kun/surrealdb";
const db = new Surreal();
await db.connect("ws://localhost:8000");
await db.connect("ws://localhost:1129"); // throws ConnectionConflictError: An attempt was made to connect to ws://localhost:1129/rpc while ws://localhost:8000/rpc was already connected.

Because .connect() will not execute concurrently in an asynchronous context, the following example will also fail to connect. Since it’s unpredictable which endpoint establishes a connection first, the error message may vary:

import { Surreal } from "@tai-kun/surrealdb";
const db = new Surreal();
await Promise.all([
db.connect("ws://localhost:8000"),
db.connect("ws://localhost:1129"),
]); // throws ConnectionConflictError

.close() instance method

Disconnects from SurrealDB. It does not throw an error if not yet connected or already disconnected. This method executes asynchronously, but will not execute concurrently with .connect() or other .close() calls within the same instance.

close(options?: ClientCloseOptions): Promise<void>

Arguments

options

Disconnection options.

force?: boolean
If true, sends an abort signal to the abort signal passed to the Surreal object’s event listeners. Event listeners are expected to terminate immediately, even if processing is incomplete.
signal?: AbortSignal
An abort signal to interrupt the connection. By default, an abort signal with a 15-second timeout is set.

Return Value

Returns a Promise object that resolves to undefined.

Example

The following example connects to SurrealDB using the WebSocket protocol and then disconnects:

import { Surreal } from "@tai-kun/surrealdb";
const db = new Surreal();
await db.connect("ws://localhost:8000");
await db.close();

.getConnectionInfo() instance method

Retrieves connection information. The connection information always holds a copied value of the internal information. Therefore, while the connection information includes a URL object, directly modifying it will not change the endpoint information held internally by the Surreal object. It is undefined if a connection has not yet been requested.

getConnectionInfo(): ConnectionInfo | undefined;

Arguments

None.

Return Value

Returns the connection information if a connection is established; otherwise, it returns undefined. The connection information includes the following items:

state: "connecting" | "open" | "closing" | "closed"
A number indicating the current connection state. Each number represents the following meaning:
endpoint: URL | null
The endpoint of the connection. null only in the disconnected state.
namespace: string | null
The currently selected namespace. null if no namespace is selected.
database: string | null
The currently selected database name. null if no database is selected.
token: string | null
The currently authenticated token. null if not signed up or signed in.

The possible values for connection information in each connection state are as shown in the following table:

stateendpointnamespacedatabasetoken
"connecting"URLnullnullnull
"open"URLstring|nullstring|nullstring|null
"closing"URLstring|nullstring|nullstring|null
"closed"nullnullnullnull

.state instance property readonly

A number indicating the current connection state.

state: "connecting" | "open" | "closing" | "closed"

For convenience, even if a connection is not established, it will be "closed" (undefined is not used).

Related: See also .getConnectionInfo().

.endpoint instance property readonly

The endpoint of the connection. null only in the disconnected state. undefined if no connection has been established.

endpoint: string | null | undefined

Related: See also .getConnectionInfo().

.namespace instance property

The currently selected namespace. null if no namespace is selected. undefined if no connection has been established.

namespace: string | null | undefined

Related: See also .getConnectionInfo().

.database instance property

The currently selected database name. null if no database is selected. undefined if no connection has been established.

database: string | null | undefined

Related: See also .getConnectionInfo().

.token instance property

The currently authenticated token. null if not signed up or signed in. undefined if no connection has been established.

token: string | null | undefined

Related: See also .getConnectionInfo().

.on() instance method

Registers an event listener.

on(
event:
| "connecting" | "open" | "closing" | "closed"
| `rpc_${RpcMethod}_${number}`
| `live_${string}`
| "error",
listener: (taskRunnerArgs, ...eventArgs) => void | PromiseLike<void>,
): void

Arguments

event

The name of the event to monitor.

"connecting" | "open" | "closing" | "closed"
Events that occur when connection information transitions or when a transition fails.
rpc_${RpcMethod}_${number}
Event that occurs when an RPC response in two-way communication occurs. RpcMethod is the name of the PRC method, such as ping or use. number is an identifier for associating requests/responses in two-way communication and takes an integer from 1 to 2^53-1. It is fixed at 0 for HTTP.
live_${string}
Event that occurs when receiving a live query event. Currently used only with the WebSocket protocol; this event is not used with the HTTP protocol. string is the UUID of the live query.
error
Error event. Currently used only with the WebSocket protocol; this event is not used with the HTTP protocol.
listener

The function to be executed when the event occurs. See also Task Emitter. The values passed to eventArgs vary depending on the event.

"connecting" | "open" | "closing" | "closed"
One of the following:
  • { state: "connecting" | "open" | "closing" | "closed" }
  • { state: "connecting" | "open" | "closing" | "closed", error: unknown }
rpc_${RpcMethod}_${number}
One of the following:
  • { id: string, result: unknown }
  • { id: string, error: { code: number, message: string } }
live_${string}
Normal mode live query:
  • { action: "CREATE" | "UPDATE" | "DELETE", result: object, record: string | object } Difference acquisition mode live query:
  • { action: "CREATE" | "UPDATE", result: object[], record: string | object }
  • { action: "DELETE", result: object, record: string | object }
error
One of the following:

Return Value

None.

.once() instance method

Similar to .on(), but captures the event only once.

once(
event:
| "connecting" | "open" | "closing" | "closed"
| `rpc_${RpcMethod}_${number}`
| `live_${string}`
| "error",
options?: TaskListenerOptions,
): StatefulPromise<unknown[]>

Arguments

event

Same as event in .on().

options

Task listener options. See Task Emitter.

Return Value

Returns a StatefulPromise that resolves with the eventArgs of the .on() task listener.

.off() instance method

Removes an event listener registered with .on().

off(
event:
| "connecting" | "open" | "closing" | "closed"
| `rpc_${RpcMethod}_${number}`
| `live_${string}`
| "error",
listener: (taskRunnerArgs, ...eventArgs) => void | PromiseLike<void>,
): void

Arguments

event

The name of the event to remove the listener from.

listener

The event listener to remove.

Return Value

None.