### Complete Typed API Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/api-class.md Illustrates setting up a typed API instance and performing type-safe GET, POST, PUT, and DELETE requests. Includes setting authentication headers. ```typescript // Define your API paths type MyApiPaths = { "/users": { get: [void, { id: string; name: string; email: string }[]]; post: [{ name: string; email: string }, { id: string; name: string; email: string }]; }; [K: `/users/${string}`]: { get: [void, { id: string; name: string; email: string }]; put: [{ name?: string; email?: string }, { id: string; name: string; email: string }]; delete: [void, void]; }; }; // Create typed API instance const db = new Surreal(); await db.connect("wss://my-instance.surreal.cloud"); const api = db.api(); // Type-safe API calls const allUsers = await api.get("/users"); const newUser = await api.post("/users", { name: "Alice", email: "alice@example.com" }); const user = await api.get("/users/alice"); const updated = await api.put(`/users/${newUser.id}`, { email: "newemail@example.com" }); await api.delete(`/users/${newUser.id}`); // With authentication header api.header("Authorization", `Bearer ${token}`); const authenticated = await api.get("/users"); ``` -------------------------------- ### Initialize SurrealDB with Default Options Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Minimal initialization of the SurrealDB client using all default options. This is the simplest way to get started. ```typescript import { Surreal } from "surrealdb"; // Minimal - uses all defaults const db = new Surreal(); ``` -------------------------------- ### Get Server Version Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Demonstrates how to fetch and log the SurrealDB server version using the `version()` method. ```typescript const info = await db.version(); console.log(info.version); // "surrealdb-2.1.0" ``` -------------------------------- ### System Access Authentication Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Example of signing in with system-level access, specifying an access method. ```typescript await db.signin({ namespace: "my_namespace", database: "my_database", username: "user", password: "pass", access: "user_access_method" }); ``` -------------------------------- ### Record Access Authentication Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Example of signing up using record-level access with custom variables like email and password. ```typescript await db.signup({ namespace: "my_namespace", database: "my_database", access: "user_access", variables: { email: "user@example.com", password: "secure_pass" } }); ``` -------------------------------- ### Define and Use User-Defined APIs Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Shows how to define custom API paths with their request and response types and then use them to interact with the database. Includes examples for GET and POST requests. ```typescript type MyApiPaths = { "/users": { get: [void, User[]]; post: [CreateRequest, User] }; [K: `/users/${string}`]: { get: [void, User]; put: [UpdateRequest, User] }; }; const api = db.api(); const users = await api.get("/users"); const user = await api.post("/users", { name: "Alice" }); const updated = await api.put("/users/alice", { email: "new@example.com" }); ``` -------------------------------- ### Token and Tokens Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Illustrates how to access the access and refresh tokens after signing in. ```typescript const tokens = await db.signin({...}); console.log(tokens.access); // Access token console.log(tokens.refresh); // Refresh token if available ``` -------------------------------- ### Root Authentication Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Demonstrates how to sign in using root-level authentication credentials. ```typescript await db.signin({ username: "root", password: "root" }); ``` -------------------------------- ### Install SurrealDB WebAssembly Browser Support Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Command to install the SurrealDB WebAssembly package for browser support. ```bash npm install @surrealdb/wasm ``` -------------------------------- ### Install SurrealDB JavaScript SDK Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Commands to install the SurrealDB JavaScript SDK using npm, pnpm, yarn, or bun. ```bash npm install surrealdb # or pnpm install surrealdb # or yarn add surrealdb # or bun add surrealdb ``` -------------------------------- ### Connect Options Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Demonstrates connecting to a SurrealDB instance with specified namespace, database, authentication, and reconnection options. ```typescript await db.connect("wss://my-instance.surreal.cloud", { namespace: "ns", database: "db", authentication: { username: "root", password: "root" }, versionCheck: true, reconnect: { enabled: true, attempts: 5 } }); ``` -------------------------------- ### Namespace Authentication Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Shows how to sign in to a specific namespace using its credentials. ```typescript await db.signin({ namespace: "my_namespace", username: "ns_user", password: "pass" }); ``` -------------------------------- ### Get Raw Response Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/api-class.md Demonstrates how to get the raw fetch Response object and access its headers. This is useful for inspecting response metadata. ```typescript const rawResponse = await api.get("/users").response(); const contentType = rawResponse.headers.get("content-type"); ``` -------------------------------- ### Database Authentication Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Illustrates signing in to a specific database within a namespace. ```typescript await db.signin({ namespace: "my_namespace", database: "my_database", username: "db_user", password: "pass" }); ``` -------------------------------- ### Live Subscription Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Demonstrates how to subscribe to live updates for a table and process incoming messages. This is useful for real-time data synchronization. ```typescript const subscription = await db.live("person"); for await (const msg of subscription) { if (msg.action === "CREATE") { console.log("Created:", msg.recordId, msg.value); } else if (msg.action === "UPDATE") { console.log("Updated:", msg.recordId, msg.value); } } ``` -------------------------------- ### Install SurrealDB SDK with npm Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Install the SurrealDB SDK using npm. This command adds the alpha version of the package to your project. ```sh # using npm npm i surrealdb@alpha # or using pnpm pnpm i surrealdb@alpha # or using yarn yarn add surrealdb@alpha # or using bun bun add surrealdb@alpha ``` -------------------------------- ### Manage Transactions in SurrealDB Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Provides an example of how to manage database transactions, including starting a transaction, committing changes, and cancelling (rolling back) changes in case of an error. ```typescript const txn = await db.beginTransaction(); try { await txn.create("user", { name: "Alice" }); await txn.create("log", { action: "user_created" }); await txn.commit(); // Apply all changes } catch (error) { await txn.cancel(); // Discard all changes throw error; } ``` -------------------------------- ### Install SurrealDB WASM Engine with bun Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB WebAssembly engine using bun. This is the first step to embedding SurrealDB in the browser. ```sh bun add @surrealdb/wasm@alpha ``` -------------------------------- ### Bearer Token Authentication Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Demonstrates signing in using a bearer token for access. ```typescript await db.signin({ access: "user_access", key: "bearer_token_value" }); ``` -------------------------------- ### Configuring SurrealDB with Remote Engines Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/utilities.md Example of initializing the SurrealDB client with remote engines created by `createRemoteEngines`. ```typescript import { Surreal, createRemoteEngines } from "surrealdb"; const db = new Surreal({ engines: createRemoteEngines() }); ``` -------------------------------- ### Building Complex Conditions with Pattern Examples Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/utilities.md Demonstrates how to build complex SurrealQL conditions using utility functions like `eq`, `gt`, `contains`, `and`, `or`, and `not`. ```APIDOC ## Building Complex Conditions ```typescript import { eq, gt, contains, and, or } from "surrealdb"; // Basic condition const activeUsers = db.select("user").where(eq("status", "active")); // Combined conditions with AND const adultActiveUsers = db.select("user").where( eq("status", "active").and(gt("age", 18)) ); // Complex OR conditions const developers = db.select("user").where( contains("roles", "developer").or(contains("roles", "admin")) ); // Negation const inactiveUsers = db.select("user").where( eq("status", "active").not() ); ``` ``` -------------------------------- ### Install SurrealDB Node.js Embedded Database Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Command to install the SurrealDB Node.js embedded database package. ```bash npm install @surrealdb/node ``` -------------------------------- ### Query Output Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Demonstrates using the `output()` method with the 'diff' option to retrieve only the changes made to a record. ```typescript const diff = await db.update("user:1") .merge({ age: 31 }) .output("diff"); ``` -------------------------------- ### Install SurrealDB WASM Engine with yarn Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB WebAssembly engine using yarn. This is the first step to embedding SurrealDB in the browser. ```sh yarn add @surrealdb/wasm@alpha ``` -------------------------------- ### Paginate Select Results Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/query-methods.md Use `start()` and `limit()` methods to implement pagination for `select` queries. `start()` specifies the index to begin selection, and `limit()` restricts the number of results returned. ```typescript const people = await db.select("person").start(10).limit(20); ``` ```typescript const first10 = await db.select("person").limit(10); ``` -------------------------------- ### startsWith() - Starts With Operation Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/utilities.md Builds a type-safe operation for checking if a string field starts with a specified prefix. ```APIDOC ## startsWith() ### Description Starts with operation. ### Method ```typescript const startsWith = (field: string, v: unknown): Expr ``` ### Parameters #### Path Parameters - **field** (string) - Required - The string field to check - **v** (unknown) - Required - The prefix to check for ### Example ```typescript const expr = startsWith("email", "admin@"); ``` ``` -------------------------------- ### Install SurrealDB WASM Engine with pnpm Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB WebAssembly engine using pnpm. This is the first step to embedding SurrealDB in the browser. ```sh pnpm i @surrealdb/wasm@alpha ``` -------------------------------- ### Install SurrealDB WASM Engine with npm Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB WebAssembly engine using npm. This is the first step to embedding SurrealDB in the browser. ```sh npm i @surrealdb/wasm@alpha ``` -------------------------------- ### Install SurrealDB Node.js Engine with bun Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB Node.js engine using bun. This engine supports running embedded databases in Node.js, Deno, and Bun. ```sh bun add @surrealdb/node@alpha ``` -------------------------------- ### SQON Primitive Types Examples Source: https://github.com/surrealdb/surrealdb.js/blob/main/packages/sqon/res/SQON_SPECIFICATION.md Demonstrates the syntax for primitive JSON-compatible types in SQON, including None, Null, Bool, Int, Float, String, Array, and Object. ```SQON NONE NULL true / false 42 3.14 / 3.14f 'hello' / "hello" [1, 2, 3] { name: 'Jane', age: 30 } ``` -------------------------------- ### Install SurrealDB Node.js Engine with npm Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB Node.js engine using npm. This engine supports running embedded databases in Node.js, Deno, and Bun. ```sh npm i @surrealdb/node@alpha ``` -------------------------------- ### Install SurrealDB Node.js Engine with yarn Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB Node.js engine using yarn. This engine supports running embedded databases in Node.js, Deno, and Bun. ```sh yarn add @surrealdb/node@alpha ``` -------------------------------- ### Install SurrealDB Node.js Engine with pnpm Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Installs the SurrealDB Node.js engine using pnpm. This engine supports running embedded databases in Node.js, Deno, and Bun. ```sh pnpm i @surrealdb/node@alpha ``` -------------------------------- ### Full Document Example in SQON-J Source: https://github.com/surrealdb/surrealdb.js/blob/main/packages/sqon/res/SQON_SPECIFICATION.md Demonstrates a complete SurrealDB record serialized in SQON-J format, including various data types like record IDs, datetimes, durations, decimals, geometry, sets, files, and nested objects. ```json { "id": { "$recordId": { "tb": "user", "id": { "$uuid": "01924b3c-f1a2-7e3d-a001-2f4b8c9d0e1f" } } }, "name": "Jane Smith", "created_at": { "$datetime": "2024-01-15T09:30:00Z" }, "session_duration": { "$duration": "1h45m" }, "balance": { "$decimal": "1042.50" }, "location": { "$geometry": { "type": "Point", "coordinates": [-0.1278, 51.5074] } }, "tags": { "$set": ["admin", "verified"] }, "avatar": { "$file": { "bucket": "uploads", "key": "/avatars/jane.png" } }, "metadata": { "score": 9.8, "flags": 3 } } ``` -------------------------------- ### JSON Patch Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Demonstrates creating a document using multiple JSON Patch operations to add and replace fields. ```typescript await db.create("document").patch([ { op: "add", path: "/title", value: "Hello" }, { op: "add", path: "/published", value: true }, { op: "replace", path: "/status", value: "draft" } ]); ``` -------------------------------- ### Subscribe to Live Queries in SurrealDB Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Demonstrates how to subscribe to real-time data changes using live queries. Includes examples for subscribing to entire tables, filtered data, and specific fields, and how to listen for updates. ```typescript // Subscribe to table const subscription = await db.live("user"); // Subscribe with filter const filtered = await db.live("user") .where(eq("status", "active")); // Subscribe to specific fields const fields = await db.live("user").fields("name", "email"); // Listen for updates for await (const message of subscription) { console.log(`${message.action} on ${message.recordId}`); console.log("Data:", message.value); } ``` -------------------------------- ### Create Records in SurrealDB Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Shows how to create new records, either with auto-generated IDs or specific IDs. Includes examples for creating records with return formats and batch creation. ```typescript // Create with auto-generated ID const user = await db.create("user", { name: "Alice", email: "alice@example.com", active: true }); // Create with specific ID const user = await db.create("user:alice", { name: "Alice", email: "alice@example.com" }); // Create with return format const diff = await db.create("user").content({...}).output("diff"); const before = await db.create("user").content({...}).output("before"); const after = await db.create("user").content({...}).output("after"); // Batch create const users = await db.insert("user").content([ { name: "Alice", email: "alice@example.com" }, { name: "Bob", email: "bob@example.com" } ]); ``` -------------------------------- ### Branch Naming Convention Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/CONTRIBUTING.md Follow this convention for naming your feature branches to provide context for your changes. It includes the type of change, the issue ID, and a brief description. ```bash bugfix-548-ensure-queries-execute-sequentially ``` -------------------------------- ### Subscribe to Live Updates in SurrealDB.js Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/query-methods.md The live method allows subscribing to real-time updates on a table. The example shows how to iterate over the subscription to receive actions, record IDs, and values. ```typescript const subscription = await db.live("person"); for await (const { action, recordId, value } of subscription) { console.log(`${action} on ${recordId}:`, value); } ``` -------------------------------- ### Import SurrealDB SDK in TypeScript Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Import the SurrealDB SDK into your TypeScript project after installation. ```ts import { Surreal } from "surrealdb"; ``` -------------------------------- ### Querying Records Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Provides examples for selecting records from tables, with options for filtering, field selection, pagination, and fetching related data. ```APIDOC ## Querying Records ### Select Retrieves records from a table. - **Simple Select**: `await db.select("user");` - **Specific Record**: `await db.select("user:1");` - **Range of Records**: `await db.select("user:1..100");` ### Filtering Applies filters to the selected records using comparison functions. - **Equality**: `await db.select("user").where(eq("active", true));` - **Greater Than**: `await db.select("user").where(gt("age", 18));` - **Contains**: `await db.select("user").where(contains("roles", "admin"));` ### Field Selection Specifies which fields to retrieve for each record. - **Select Fields**: `await db.select("user").fields("name", "email");` ### Pagination Implements pagination for retrieving records in chunks. - **Page 1**: `await db.select("user").start(0).limit(10);` - **Page 2**: `await db.select("user").start(10).limit(10);` ### Fetching Related Data Retrieves a record along with its related data. - **Fetch Related**: `await db.select("user:1").fetch("posts");` ``` -------------------------------- ### Register and Connect to Node.js Embedded Databases Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Configures the SurrealDB client to use the Node.js engine and demonstrates connecting to in-memory, RocksDB, and SurrealKV instances. Ensure '@surrealdb/node' is installed. ```typescript import { createNodeEngines } from "@surrealdb/node"; import { Surreal } from "surrealdb"; // Register the Node.js engine const db = new Surreal({ engines: createNodeEngines(), }); // Connect to an in-memory instance await db.connect("mem://"); // Connect to an RocksDB instance await db.connect("rocksdb://path/to/storage.db"); // Connect to an SurrealKV instance await db.connect("surrealkv://path/to/storage.db"); // Connect to an SurrealKV instance with versioning await db.connect("surrealkv+versioned://path/to/storage.db"); ``` -------------------------------- ### Basic Transaction Pattern Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/transaction.md A fundamental example of using a transaction to perform multiple create operations and then commit or cancel them. It includes basic logging for success and rollback. ```typescript const txn = await db.beginTransaction(); try { await txn.create("user:1", { name: "Alice" }); await txn.create("user:2", { name: "Bob" }); await txn.commit(); console.log("Transaction committed"); } catch (error) { await txn.cancel(); console.error("Transaction rolled back:", error); } ``` -------------------------------- ### Check SurrealDB Version Source: https://github.com/surrealdb/surrealdb.js/blob/main/CONTRIBUTING.md Run the 'surreal version' command to get the SurrealDB version identifier. This is required when reporting security vulnerabilities. ```bash surreal version ``` -------------------------------- ### Register and Connect to In-Memory WASM Engine Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Configures the SurrealDB client to use the WebAssembly engine and connects to an in-memory database instance. Ensure '@surrealdb/wasm' is installed. ```typescript import { createWasmEngines } from "@surrealdb/wasm"; import { Surreal } from "surrealdb"; // Register the WebAssembly engine const db = new Surreal({ engines: createWasmEngines(), }); // Connect to an in-memory instance await db.connect("mem://"); // Connect to an IndexedDB instance await db.connect("indxdb://demo"); ``` -------------------------------- ### SQON SurrealDB-Specific Types Examples Source: https://github.com/surrealdb/surrealdb.js/blob/main/packages/sqon/res/SQON_SPECIFICATION.md Illustrates the custom syntax for SurrealDB-specific data types in SQON, such as Decimal, Duration, Datetime, UUID, Set, Bytes, Table, Record ID variants, File, Range, and Geometry. ```SQON 3.14159265358979dec 1h30m / 2w3d / 100ms d"2024-01-15T09:30:00Z" u"01924b3c-f1a2-7e3d-a001-2f4b8c9d0e1f" {1, 2, 3} b"48656C6C6F" person (bare identifier) user:abc123 user:42 user:⟨01924b3c-f1a2-7e3d-a001-2f4b8c9d0e1f⟩ user:{ name: 'john', age: 30 } temperature:['London', d'2025-02-13'] f"bucket:/path/to/file.txt" 0..10 / 0..=10 / 0>..10 (-122.4194, 37.7749) ``` -------------------------------- ### Initializing SurrealDB with Diagnostics Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/utilities.md Demonstrates how to initialize the SurrealDB client with engines wrapped by `applyDiagnostics` to log internal events. ```typescript import { Surreal, createRemoteEngines, applyDiagnostics } from "surrealdb"; const db = new Surreal({ engines: applyDiagnostics(createRemoteEngines(), (event) => { console.log("Event:", event.type, event.payload); }) }); ``` -------------------------------- ### Invoke GET Request Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/api-class.md Make a GET request to a specified API path. This is useful for retrieving data. ```typescript const users = await api.get("/users"); const user = await api.get("/users/123"); ``` -------------------------------- ### Initialize with WebAssembly Embedded Engine Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Set up the SDK with the WebAssembly embedded engine for browser-based local storage. Supports IndexedDB and in-memory databases. ```typescript import { Surreal } from "surrealdb"; import { createWasmEngines } from "@surrealdb/wasm"; const db = new Surreal({ engines: createWasmEngines() }); await db.connect("indexdb://demo"); ``` -------------------------------- ### Authenticate with SurrealDB Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Demonstrates different authentication methods including root user, namespace/database user, access key, and token-based authentication. Also shows how to sign up for a new record. ```typescript // Root user await db.signin({ username: "root", password: "root" }); // Namespace/database user await db.signin({ namespace: "ns", database: "db", username: "user", password: "pass" }); // Access method await db.signin({ access: "method", key: "token" }); // Token-based await db.signin({ access: "eyJ0..." }); // New record signup await db.signup({ namespace: "ns", database: "db", access: "user_access", variables: { email: "user@example.com", password: "pass" } }); ``` -------------------------------- ### Instantiate SurrealApi Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/api-class.md Create an API instance using `db.api()` or `session.api()`. You can optionally specify a prefix for the API paths. ```typescript const api = db.api(); // or with prefix const api = db.api("/v1"); ``` -------------------------------- ### Initialize SurrealDB with Custom Engines Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Initialize the SurrealDB client with custom engine implementations for various protocols. This allows for specialized protocol handling. ```typescript import { Surreal } from "surrealdb"; // With custom engines const db = new Surreal({ engines: createRemoteEngines() }); ``` -------------------------------- ### connect() Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal.md Establishes a connection to a SurrealDB instance using the provided URL and optional connection settings. ```APIDOC ## connect() ### Description Establishes a connection to a SurrealDB instance using the provided URL and optional connection settings. ### Signature ```typescript async connect(url: string | URL, opts?: ConnectOptions): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **url** (`string | URL`) - Required - The endpoint to connect to (e.g., `"wss://my-instance.surreal.cloud"`, `"mem://"`, `"http://localhost:8000"`). - **opts** (`ConnectOptions`) - Optional - Connection options including namespace, database, authentication, and reconnect settings. ### Request Example ```typescript await db.connect("wss://my-instance.aws-euw1.surreal.cloud"); // With options await db.connect("wss://my-instance.aws-euw1.surreal.cloud", { namespace: "my_namespace", database: "my_database", authentication: { username: "root", password: "root" } }); ``` ### Response #### Success Response (200) - **(void)** - Resolves when the connection is established. #### Throws - `UnsupportedVersionError` — If version check fails and is enabled - `UnexpectedConnectionError` — If connection fails ``` -------------------------------- ### SQON Range Syntax Source: https://github.com/surrealdb/surrealdb.js/blob/main/packages/sqon/res/SQON_SPECIFICATION.md Illustrates the various syntaxes for defining ranges in SQON, including inclusive/exclusive bounds and unbounded ranges. ```SQON a..b a..=b a>..b a>..=b a.. ..b .. ``` -------------------------------- ### Clone the Repository Source: https://github.com/surrealdb/surrealdb.js/blob/main/CONTRIBUTING.md Use git clone to download the SurrealDB repository to your local machine. This is the first step in contributing to the project. ```bash git clone ``` -------------------------------- ### Create and Manage Independent Sessions Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Demonstrates how to create new sessions, fork existing ones, and assign distinct namespace and database contexts to each session. This allows for independent operations on the same connection. ```typescript const session1 = await db.newSession(); const session2 = session1.forkSession(); // Clone of session1 await session1.use({ namespace: "ns1", database: "db1" }); await session2.use({ namespace: "ns2", database: "db2" }); // Both sessions operate independently on the same connection ``` -------------------------------- ### Initialize SurrealDB with Custom Fetch and WebSocket Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Initialize the SurrealDB client using custom implementations for the fetch and WebSocket APIs. This is useful for environments with specific networking requirements. ```typescript import { Surreal } from "surrealdb"; // With custom fetch/WebSocket const db = new Surreal({ fetchImpl: customFetch, websocketImpl: CustomWebSocket }); ``` -------------------------------- ### Authentication Methods Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Demonstrates various ways to authenticate with the SurrealDB server using the `signin` and `signup` methods. ```APIDOC ## Authentication ### Signin Allows users to sign in to the database. - **Root User**: `await db.signin({ username: "root", password: "root" });` - **Namespace/Database User**: `await db.signin({ namespace: "ns", database: "db", username: "user", password: "pass" });` - **Access Key**: `await db.signin({ access: "method", key: "token" });` - **Token-Based**: `await db.signin({ access: "eyJ0..." });` ### Signup Allows new users to sign up for an account. - **New Record Signup**: `await db.signup({ namespace: "ns", database: "db", access: "user_access", variables: { email: "user@example.com", password: "pass" } });` ``` -------------------------------- ### beginTransaction() Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal-session.md Initiates a new transaction scoped to the current session, enabling atomic execution of multiple SurrealQL queries. ```APIDOC ## beginTransaction() ### Description Initiates a new transaction scoped to the current session, enabling atomic execution of multiple SurrealQL queries. ### Method `async beginTransaction(): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const txn = await session.beginTransaction(); try { await txn.create("users", { name: "Alice" }); await txn.create("posts", { title: "Hello" }); await txn.commit(); } catch (error) { await txn.cancel(); } ``` ### Response #### Success Response (200) - **SurrealTransaction** - A new transaction instance #### Response Example ```typescript // Example response is the transaction object itself, not a JSON representation // const txn = ... ``` ``` -------------------------------- ### RecordResult Type Example Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/types.md Illustrates how `RecordResult` types a selected record, ensuring the presence and correct typing of the `id` field. ```typescript type Person = { name: string; age: number; }; const result = await db.select("person:1"); // Type: RecordResult = { id: RecordId<"person", string>, name: string, age: number } ``` -------------------------------- ### Initialize with Node.js Embedded Engine Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Configure the SDK to use the Node.js embedded engine for local storage. Supports various database backends like RocksDB. ```typescript import { Surreal } from "surrealdb"; import { createNodeEngines } from "@surrealdb/node"; const db = new Surreal({ engines: createNodeEngines() }); await db.connect("rocksdb://./database.db"); ``` -------------------------------- ### Starts With Operation with startsWith() Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/utilities.md Use `startsWith()` to check if a string field begins with a specific prefix. This is commonly used for prefix-based searches. ```typescript const expr = startsWith("email", "admin@"); ``` -------------------------------- ### Get Connection Status Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal.md Retrieve the current connection status of the SurrealDB client. The status can be one of 'disconnected', 'connecting', 'reconnecting', or 'connected'. ```typescript console.log(db.status); // "connected" ``` -------------------------------- ### live() Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal.md Creates a new live subscription to a specific table, allowing real-time data updates. ```APIDOC ## live() ### Description Create a new live subscription to a specific table. ### Method `live(what: LiveResource): ManagedLivePromise` ### Returns `ManagedLivePromise` — For full API, see [ManagedLivePromise](./managed-live-promise.md). ``` -------------------------------- ### import() Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal.md Imports an existing export (SurrealQL format) into the database. ```APIDOC ## import() ### Description Import an existing export into the database. ### Method `async import(input: string | Blob | ReadableStream): Promise` ### Parameters #### Request Body - **input** (string | Blob | ReadableStream) - Required - The data to import (SQL export format) ### Example ```typescript const sqlDump = "CREATE users CONTENT {...}"; await db.import(sqlDump); ``` ``` -------------------------------- ### SurrealDB JavaScript SDK Basic Usage Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Demonstrates the basic pattern for using the SurrealDB JavaScript SDK, including connecting, selecting namespace/database, authenticating, executing queries, subscribing to live updates, and closing the connection. ```typescript import { Surreal } from "surrealdb"; // 1. Create instance const db = new Surreal(); // 2. Connect await db.connect("wss://my-instance.surreal.cloud"); // 3. Select namespace/database await db.use({ namespace: "ns", database: "db" }); // 4. Authenticate await db.signin({ username: "root", password: "root" }); // 5. Execute queries const users = await db.select("user"); const created = await db.create("user", { name: "Alice" }); const updated = await db.update("user:1").merge({ active: true }); // 6. Subscribe to updates const subscription = await db.live("user"); for await (const { action, value } of subscription) { console.log(`User ${action}:`, value); } // 7. Close connection await db.close(); ``` -------------------------------- ### Initialize with Default Remote Engines Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Create and use the default engines for remote connections. This is the standard way to connect to a SurrealDB instance over the network. ```typescript import { Surreal, createRemoteEngines } from "surrealdb"; const db = new Surreal({ engines: createRemoteEngines() }); await db.connect("wss://my-instance.surreal.cloud"); ``` -------------------------------- ### Signup with Access Record and Variables Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal-session.md Registers a new user record in SurrealDB, specifying namespace, database, access method, and custom variables. ```typescript const tokens = await session.signup({ namespace: "my_ns", database: "my_db", access: "user_access", variables: { email: "user@example.com", password: "secure_pass" } }); ``` -------------------------------- ### HTTP Method Functions Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/api-class.md Provides methods for invoking standard HTTP requests (GET, POST, PUT, PATCH, DELETE, TRACE) against custom API paths. ```APIDOC ## HTTP Method Functions ### get() ```typescript get

>( path: P ): ApiPromise> ``` Invoke a GET request to the specified API path. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | `string` | Yes | The API path to invoke | **Returns:** `ApiPromise` — Resolves with the response data **Example:** ```typescript const users = await api.get("/users"); const user = await api.get("/users/123"); ``` ### post() ```typescript post

>( path: P, body?: RequestBody ): ApiPromise, ResponseBody> ``` Invoke a POST request to the specified API path. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | `string` | Yes | The API path to invoke | | `body` | `unknown` | No | The request body | **Returns:** `ApiPromise` — Resolves with the response data **Example:** ```typescript const newUser = await api.post("/users", { name: "Alice", email: "alice@example.com" }); ``` ### put() ```typescript put

>( path: P, body?: RequestBody ): ApiPromise, ResponseBody> ``` Invoke a PUT request. **Example:** ```typescript const updated = await api.put("/users/123", { name: "Alice Updated" }); ``` ### patch() ```typescript patch

>( path: P, body?: RequestBody ): ApiPromise, ResponseBody> ``` Invoke a PATCH request. **Example:** ```typescript const updated = await api.patch("/users/123", { email: "newemail@example.com" }); ``` ### delete() ```typescript delete

>( path: P, body?: RequestBody ): ApiPromise, ResponseBody> ``` Invoke a DELETE request. **Example:** ```typescript await api.delete("/users/123"); ``` ### trace() ```typescript trace

>( path: P ): ApiPromise> ``` Invoke a TRACE request. ``` -------------------------------- ### Surreal Constructor Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal.md Initializes a new SurrealDB.js client instance. Options can be provided for custom driver configurations. ```APIDOC ## Constructor Surreal ### Description Initializes a new SurrealDB.js client instance. Options can be provided for custom driver configurations. ### Signature ```typescript constructor(options?: DriverOptions) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`DriverOptions`) - Optional - Driver-wide configuration options including engines, codecs, and custom implementations. ### Request Example ```typescript import { Surreal } from "surrealdb"; const db = new Surreal(); // Or with custom options const db = new Surreal({ engines: createRemoteEngines(), codecOptions: { /* codec options */ } }); ``` ### Response None ``` -------------------------------- ### Connect Using Environment Variables Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Configure connection parameters such as endpoint, namespace, database, username, and password using environment variables. Provides a fallback to default values if variables are not set. ```typescript const endpoint = process.env.SURREAL_URL || "wss://localhost:8000"; const namespace = process.env.SURREAL_NS || "default"; const database = process.env.SURREAL_DB || "default"; const db = new Surreal(); await db.connect(endpoint, { namespace, database, authentication: { username: process.env.SURREAL_USER || "root", password: process.env.SURREAL_PASS || "root" } }); ``` -------------------------------- ### Initialize SurrealDB with Node.js Embedded Engines Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Initialize the SurrealDB client for Node.js environments using embedded engine implementations. This enables local data storage with engines like RocksDB. ```typescript import { Surreal } from "surrealdb"; import { createNodeEngines } from "@surrealdb/node"; const db = new Surreal({ engines: createNodeEngines() }); await db.connect("mem://"); // In-memory await db.connect("rocksdb://path/to/db"); // RocksDB ``` -------------------------------- ### Query Result Methods Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/query-methods.md Methods available on all query promises for handling results, including collecting all results, getting responses with success/error info, streaming individual frames, and returning JSON-compatible structures. ```APIDOC ## Query Result Methods All query promises support these methods for result handling: ### collect() ```typescript async collect(...queries: number[]): Promise> ``` Collect and return all results at once. If any query fails, rejects. **Example:** ```typescript const [people, count] = await db.query( "SELECT * FROM person; SELECT count(*) FROM person" ).collect<[Person[], number]>(); ``` ### responses() ```typescript async responses(...queries: number[]): Promise> ``` Collect responses with success/error information. **Example:** ```typescript const [userResponse, postResponse] = await db.query(` SELECT * FROM user; SELECT * FROM post; `).responses<[User[], Post[]]>(); if (userResponse.success) { console.log(userResponse.result); } ``` ### stream() ```typescript async *stream(): AsyncIterable> ``` Stream individual frames (values, errors, done). **Example:** ```typescript for await (const frame of db.select("table").stream()) { if (frame.isValue(0)) { console.log("Value:", frame.value); } else if (frame.isError(0)) { console.error("Error:", frame.error); } else if (frame.isDone(0)) { console.log("Done with stats:", frame.stats); } } ``` ### json() ```typescript json(): Promise<..., true> ``` Return results as JSON-compatible structures (loses type info). ``` -------------------------------- ### Export SurrealDB Configuration Options Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/configuration.md Demonstrates how to export different parts of a SurrealDB database configuration, including full exports, schema-only exports, and exports of specific tables. ```typescript // Export everything const fullExport = await db.export({ users: true, accesses: true, params: true, functions: true, analyzers: true, apis: true, buckets: true, modules: true, configs: true, tables: true, // All tables versions: true, records: true, sequences: true, v3: false }); // Export only schema (no data) const schemaExport = await db.export({ users: true, accesses: true, params: true, functions: true, analyzers: true, apis: true, tables: true, records: false, // No record data versions: false }); // Export specific tables const specificExport = await db.export({ tables: ["users", "posts"], // Only these tables records: true }); ``` -------------------------------- ### Update Records in SurrealDB Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md Demonstrates updating records using various methods like merge, replace, content, and patch. Includes examples for updating specific records, conditional updates, and batch updates. ```typescript // Update specific record const updated = await db.update("user:1").merge({ active: false }); // Update with condition const updated = await db.update("user") .merge({ status: "verified" }) .where(eq("verified", true)); // Update all in table const updated = await db.update("user").content({ ...fullData }); // Different mutation types await db.update("user:1").merge({...}); // Shallow merge await db.update("user:1").replace({...}); // Deep replace await db.update("user:1").content({...}); // Replace all await db.update("user:1").patch([...]); // JSON Patch // Batch update const results = await db.upsert("user").content([ { id: "user:1", ...data1 }, { id: "user:2", ...data2 } ]); ``` -------------------------------- ### Create and Commit a Transaction Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/transaction.md Demonstrates the basic workflow of creating a transaction, executing multiple operations, and committing them atomically. Includes error handling for cancellation. ```typescript const txn = await session.beginTransaction(); try { // Execute multiple operations await txn.create("users", { name: "Alice" }); await txn.create("posts", { title: "Hello" }); // Commit changes await txn.commit(); } catch (error) { // Discard changes await txn.cancel(); } ``` -------------------------------- ### Create Record with Content Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/query-methods.md Use the `create()` method combined with `content()` to create a new record in the database with specified data. The `content()` method sets the complete data for the new record. ```typescript const person = await db.create("person") .content({ name: "Alice", email: "alice@example.com" }); ``` -------------------------------- ### Import SurrealDB SDK for Browser with CDN Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Import the SurrealDB SDK for browser environments using a CDN link. Note: This bundle is not recommended for production use. ```ts import Surreal from "https://unpkg.com/surrealdb"; // or import Surreal from "https://cdn.jsdelivr.net/npm/surrealdb"; ``` -------------------------------- ### Begin Transaction Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/surreal-session.md Initiates a new transaction scoped to the current session, enabling atomic execution of multiple queries. The transaction must be explicitly committed or cancelled. ```typescript const txn = await session.beginTransaction(); try { await txn.create("users", { name: "Alice" }); await txn.create("posts", { title: "Hello" }); await txn.commit(); } catch (error) { await txn.cancel(); } ``` -------------------------------- ### Configuration Methods: header() Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/api-reference/api-class.md Configure a header for all requests sent by this API instance. Headers can be set or removed by passing `null` as the value. ```APIDOC ## Configuration Methods ### header() ```typescript header(name: string, value: string | null): void ``` Configure a header for all requests sent by this API instance. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `name` | `string` | Yes | The name of the header | | `value` | `string \| null` | Yes | The value (or null to remove) | **Example:** ```typescript api.header("Authorization", "Bearer token123"); api.header("X-Custom", "value"); // Remove a header api.header("X-Custom", null); ``` ``` -------------------------------- ### Connect and Authenticate with SurrealDB Source: https://github.com/surrealdb/surrealdb.js/blob/main/README.md Instantiate the SurrealDB client, connect to a remote instance using a WebSocket URI, select a namespace and database, and sign in with user credentials. ```ts import { Surreal, RecordId, Table } from "surrealdb"; // Instantiate the SurrealDB client const db = new Surreal(); // Connect to the specified instance await db.connect("wss://my-instance.aws-euw1.surrealdb.cloud"); // Select a specific namespace / database await db.use({ namespace: "test", database: "test" }); // Signin as a namespace, database, root, or record user await db.signin({ username: "root", password: "root", }); ``` -------------------------------- ### Query Methods Source: https://github.com/surrealdb/surrealdb.js/blob/main/_autodocs/README.md A complete reference for SurrealQL query operations including SELECT, CREATE, UPDATE, DELETE, INSERT, UPSERT, RELATE, and LIVE queries. ```APIDOC ## Query Methods ### Description Complete reference for SELECT, CREATE, UPDATE, DELETE, INSERT, UPSERT, RELATE, and LIVE operations. ### Methods - `select(id: string)`: Query records with filtering, pagination, field selection. - `create(table: string, data: object)`: Create new records with content or patch mutations. - `update(id: string)`: Update records with merge, replace, or patch operations. - `delete(id: string)`: Delete records with optional output configuration. - `insert(table: string, data: object | object[])`: Batch insert multiple records. - `upsert(table: string, data: object | object[])`: Create or update multiple records. - `relate(from: string, to: string, edge?: object)`: Create relationships (edges) between records. - `live(table: string, query?: object)`: Subscribe to real-time updates via live queries. - `query(surql: string, bindings?: object)`: Execute raw SurrealQL with parameter binding. ```