### Start Example App with Bun Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/bottom.md Run this command to start the example application in development mode. This is useful for testing features in a live environment. ```bash bun run dev ``` -------------------------------- ### Install and Start SurrealDB Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/examples/sk/README.md Installs SurrealDB using curl and starts a memory-based instance with root credentials. ```bash # Install SurrealDB curl -sSf https://install.surrealdb.com | sh # Start SurrealDB surreal start --log info --user root --pass root memory ``` -------------------------------- ### Start SvelteKit Development Server Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/examples/sk/README.md Starts the SvelteKit development server from the examples/sk directory. Use 'bun run dev:adapter' to rebuild the adapter before starting. ```bash # From examples/sk directory bun run dev # or bun run dev:adapter # Rebuilds adapter and starts dev server ``` -------------------------------- ### Development and Testing Commands Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/README.md Commands for managing dependencies, building the adapter, running unit and integration tests, and starting the example application. Integration tests require SurrealDB to be running. ```bash # Install dependencies bun install # Build the adapter bun run build # Run adapter unit tests bun run test:adapter # Run integration tests (requires SurrealDB) bun run test:integration # Run all tests bun run test:all # Start example app bun run dev ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/bottom.md Use this command to install all necessary project dependencies before building or testing. ```bash bun install ``` -------------------------------- ### Configure SurrealDB Adapter with Better Auth Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/configuration.md Integrate the SurrealDB adapter into Better Auth by passing it in the `database` option. This example shows setup with email/password and GitHub social providers. ```typescript import { betterAuth } from "better-auth"; import { surrealdbAdapter } from "surreal-better-auth"; import Surreal from "surrealdb"; const db = new Surreal(); await db.connect("ws://localhost:8000"); await db.use({ namespace: "production", database: "myapp" }); export const auth = betterAuth({ database: surrealdbAdapter(db, { debugLogs: process.env.NODE_ENV === "development", idGenerator: "surreal.UUIDv7", usePlural: false, allowPassingId: false, }), emailAndPassword: { enabled: true, }, socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, }, // Other Better Auth configuration... }); ``` -------------------------------- ### Install Surreal Better Auth Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Install the necessary packages for surreal-better-auth, better-auth, and surrealdb. ```bash npm install surreal-better-auth better-auth surrealdb ``` -------------------------------- ### SurrealDB Adapter Configuration Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/types.md An example demonstrating how to configure the SurrealDB adapter with specific settings for debug logs, ID generation, plural table names, and ID passing. ```typescript const config: SurrealDBAdapterConfig = { debugLogs: { create: true, findOne: true, update: true, updateMany: false, delete: false, deleteMany: false, findMany: false, count: false, }, idGenerator: "surreal.UUIDv7", usePlural: true, allowPassingId: false, }; ``` -------------------------------- ### Example Debug Log Output Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/errors-and-debugging.md This example demonstrates the typical output format for debug logs, showing create, findOne, and update operations. ```text ### [0/#] create (PreparedQuery): CREATE type::thing('user', rand::uuid::v7()) CONTENT { email: "user@example.com", name: "John Doe" } ### [0/#] findOne (PreparedQuery): SELECT id, email, name FROM ONLY user WHERE email = "user@example.com" LIMIT 1 ### [0/#] update (PreparedQuery): UPDATE ONLY user:abc123 MERGE { name: "Jane Doe" } RETURN AFTER ``` -------------------------------- ### Install Dependencies and Build Adapter Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/examples/sk/README.md Installs project dependencies from the monorepo root and builds the adapter package. ```bash # From monorepo root bun install bun run build # Build the adapter package ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/examples/sk/README.md Installs the necessary Playwright browsers for end-to-end testing. ```bash bunx playwright install ``` -------------------------------- ### Install surreal-better-auth with Bun Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/packages/surreal-better-auth/README.md Install the surreal-better-auth package using the Bun package manager. ```bash bun add surreal-better-auth ``` -------------------------------- ### Log Output Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/configuration.md Illustrates the format of debug logs generated by the adapter, showing the SurrealQL query, method name, and parameter bindings. ```text ### [0/#] create (PreparedQuery): CREATE type::thing('user', rand::uuid::v7()) CONTENT {...} ``` -------------------------------- ### Basic SurrealDB and Better Auth Setup Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Connect to a SurrealDB instance and initialize the betterAuth instance with the surrealdbAdapter. Ensure you have SurrealDB running and accessible. ```typescript import { betterAuth } from "better-auth"; import { surrealdbAdapter } from "surreal-better-auth"; import Surreal from "surrealdb"; // Connect to SurrealDB const db = new Surreal(); await db.connect("ws://localhost:8000"); await db.use({ namespace: "production", database: "myapp" }); // Create auth instance export const auth = betterAuth({ database: surrealdbAdapter(db, { idGenerator: "surreal.UUIDv7", debugLogs: false, }), emailAndPassword: { enabled: true, }, }); ``` -------------------------------- ### Install surreal-better-auth with npm, yarn, or pnpm Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/packages/surreal-better-auth/README.md Install the surreal-better-auth package using npm, yarn, or pnpm. ```bash # Using other package managers npm install surreal-better-auth yarn add surreal-better-auth pnpm add surreal-better-auth ``` -------------------------------- ### SurrealDBAdapterConfig with IdGenerator Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/types.md Example of configuring SurrealDBAdapterConfig to use a specific ID generation strategy. This example uses SurrealDB's time-based UUIDv7. ```typescript const config: SurrealDBAdapterConfig = { idGenerator: "surreal.UUIDv7", // Use SurrealDB to generate time-based UUIDs }; ``` -------------------------------- ### Run Adapter Unit Tests with Bun Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/bottom.md Execute this command to run the unit tests for the adapter. Ensure dependencies are installed and the adapter is built if necessary. ```bash bun run test:adapter ``` -------------------------------- ### Starts With Substring Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of checking if a string field begins with a specific substring. Useful for prefix matching. ```typescript { field: "email", operator: "starts_with", value: "admin@" } ``` -------------------------------- ### Example Usage of generateSchema Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-schema.md Demonstrates how to use the `generateSchema` function with custom mapping functions and how to write the generated schema to a file. ```typescript import { generateSchema } from "surreal-better-auth"; const result = generateSchema({ file: "migrations/schema.surql", tables: betterAuthTables, getModelName: (model) => model === "user" ? "users" : model, getFieldName: (opts) => opts.field, // or custom naming getReferencedModel: (table, field) => { // Custom logic to determine referenced table if (field === "userId") return "users"; return null; }, }); // result.path === "migrations/schema.surql" // result.code contains full SurrealQL schema // result.overwrite === true // Write to file and apply to database fs.writeFileSync(result.path, result.code); // Then: PASTE into Surrealist or execute via surrealdb CLI ``` -------------------------------- ### Initialize Better Auth with SurrealDB Adapter Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-adapter.md Example of initializing a Better Auth instance using the surrealdbAdapter. Ensure SurrealDB connection and namespace/database are set up prior to this. ```typescript import { betterAuth } from "better-auth"; import { surrealdbAdapter } from "surreal-better-auth"; import Surreal from "surrealdb"; // Initialize SurrealDB connection const db = new Surreal(); await db.connect("ws://localhost:8000"); await db.use({ namespace: "production", database: "myapp" }); // Create auth instance export const auth = betterAuth({ database: surrealdbAdapter(db, { idGenerator: "surreal.UUIDv4", debugLogs: true, }), emailAndPassword: { enabled: true, }, }); ``` -------------------------------- ### Multiple OR Conditions Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Illustrates combining conditions with explicit OR logic. At least one of the conditions needs to be met. ```typescript where: [ { field: "role", operator: "eq", value: "admin", connector: "OR" }, { field: "role", operator: "eq", value: "moderator" } ] ``` -------------------------------- ### Multiple AND Conditions Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Shows how to combine two conditions using the default AND logic. Both conditions must be met for a record to be selected. ```typescript where: [ { field: "emailVerified", operator: "eq", value: true }, { field: "status", operator: "ne", value: "deleted" } ] ``` -------------------------------- ### Configure Surreal-Better-Auth Adapter Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/packages/surreal-better-auth/README.md Configures the better-auth library with the SurrealDB adapter. This setup enables email/password authentication and integrates social providers like GitHub. ```typescript // lib/auth.ts import { betterAuth } from "better-auth"; import { surrealAdapter } from "surreal-better-auth"; import { db } from "./db"; export const auth = betterAuth({ database: surrealAdapter(db), emailAndPassword: { enabled: true, }, socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, }, }); ``` -------------------------------- ### Generate SurrealDB Schema Manually Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/examples/sk/README.md Manually generates the SurrealDB schema file (schema.surql). The test setup automatically handles schema loading or generation. ```bash # Generate schema manually (creates schema.surql) bun run create:schema ``` -------------------------------- ### Build the Adapter with Bun Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/bottom.md Run this command to compile the adapter code. This is typically done after making changes or before testing. ```bash bun run build ``` -------------------------------- ### Build and Preview SvelteKit Application Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/examples/sk/README.md Creates a production build of the SvelteKit application and then previews the production build. ```bash # To create a production build: bun run build # Preview the production build: bun run preview ``` -------------------------------- ### Set up SurrealDB Connection Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/packages/surreal-better-auth/README.md Establishes a connection to your SurrealDB instance and selects the namespace and database. Ensure SurrealDB is running and accessible. ```typescript // lib/db.ts import Surreal from "surrealdb"; const db = new Surreal(); await db.connect("ws://localhost:8000"); await db.use({ namespace: "production", database: "myapp" }); export { db }; ``` -------------------------------- ### Less Than Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of a less than comparison for the 'age' field. Use this for numerical ranges. ```typescript { field: "age", operator: "lt", value: 65 } ``` -------------------------------- ### Greater Than Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of a greater than comparison for the 'age' field. Use this for numerical ranges. ```typescript { field: "age", operator: "gt", value: 18 } ``` -------------------------------- ### Inequality Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of a not equal check for the 'status' field. Use this to exclude specific values. ```typescript { field: "status", operator: "ne", value: "inactive" } ``` -------------------------------- ### File Structure Overview Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/00-START-HERE.md Lists the file locations for documentation within the Surreal Better Auth project. ```bash ├── 00-START-HERE.md ← You are here ├── README.md ← Overview ├── INDEX.md ← Navigation guide ├── api-reference-adapter.md ← Main function ├── api-reference-helpers.md ← Helper functions ├── api-reference-schema.md ← Schema generation ├── types.md ← Type definitions ├── configuration.md ← Configuration ├── querying-patterns.md ← Query examples ├── errors-and-debugging.md ← Error handling └── GENERATION_SUMMARY.txt ← This generation report ``` -------------------------------- ### Equality Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of a simple equality check for the 'status' field. Use this for exact matches. ```typescript { field: "status", operator: "eq", value: "active" } ``` -------------------------------- ### Ends With Substring Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of checking if a string field ends with a specific substring. Useful for suffix matching. ```typescript { field: "domain", operator: "ends_with", value: ".com" } ``` -------------------------------- ### Verify Adapter Configuration and Schema Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/errors-and-debugging.md Inspect the adapter's configuration, the database schema (tables), and function mappings to ensure they align with expectations. ```typescript // Check adapter config console.log(config); // Check schema console.log(tables); // Check function mappings console.log(getModelName("user")); // Should return actual table name console.log(getFieldName({ model: "user", field: "email" })); // Should return field name ``` -------------------------------- ### Less Than or Equal To Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of a less than or equal to comparison for the 'age' field. Use this for inclusive numerical ranges. ```typescript { field: "age", operator: "lte", value: 65 } ``` -------------------------------- ### Initialize Adapter with Basic Configuration Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/configuration.md Initializes the SurrealDB adapter with common configuration options like debug logging, ID generation strategy, and plural table names. ```typescript const adapter = surrealdbAdapter(db, { debugLogs: true, idGenerator: "surreal.UUIDv7", usePlural: false, allowPassingId: false, }); ``` -------------------------------- ### Greater Than or Equal To Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of a greater than or equal to comparison for the 'age' field. Use this for inclusive numerical ranges. ```typescript { field: "age", operator: "gte", value: 18 } ``` -------------------------------- ### Contains Substring Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of checking if a string field contains a specific substring. Useful for partial text matching. ```typescript { field: "bio", operator: "contains", value: "developer" } ``` -------------------------------- ### Fork and Clone Repository Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/CONTRIBUTING.md Clone the repository, set up dependencies, and create a new branch for your feature or bug fix. ```bash # Fork the repo on GitHub, then: git clone https://github.com/YOUR-USERNAME/surreal-better-auth.git cd surreal-better-auth bun run setup # Create a new branch for your changes git checkout -b feature/your-feature-name # or for bug fixes: git checkout -b fix/issue-description ``` -------------------------------- ### Main Export Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md The primary function to initialize the SurrealDB adapter. It takes a SurrealDB instance and an optional configuration object to set up the database adapter. ```APIDOC ## surrealdbAdapter ### Description Initializes the SurrealDB adapter with a SurrealDB instance and configuration. ### Signature ```typescript export function surrealdbAdapter(db: Surreal, config?: SurrealDBAdapterConfig): DatabaseAdapter ``` ### Parameters - **db** (Surreal) - Required - The SurrealDB instance to use. - **config** (SurrealDBAdapterConfig) - Optional - Configuration options for the adapter. ``` -------------------------------- ### Count Records Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Use `count` to get the total number of records matching specific criteria. This is efficient for aggregate operations. ```typescript const count = await adapter.count({ model: "user", where: [{ field: "emailVerified", operator: "eq", value: true }] }); // Returns: 1543 (number of verified users) ``` ```surql SELECT count() FROM user WHERE emailVerified = true GROUP ALL ``` -------------------------------- ### Run All Adapter Tests Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/CONTRIBUTING.md Execute all tests for the adapter to ensure its functionality. This command is used during the development workflow to verify changes. ```bash # Run all adapter tests bun run test:adapter ``` -------------------------------- ### Run Integration Tests with Bun Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/bottom.md Use this command to run integration tests. Note that this requires a running SurrealDB instance. ```bash bun run test:integration ``` -------------------------------- ### Single Where Condition Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Demonstrates a single equality condition for filtering records where 'emailVerified' is true. This is the simplest form of a query filter. ```typescript where: [{ field: "emailVerified", operator: "eq", value: true }] ``` -------------------------------- ### buildSpecialCasesMapping() Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-helpers.md Builds a mapping of special field-to-table references based on declarative rules, including optional conditions for dynamic referencing. ```APIDOC ## buildSpecialCasesMapping() ### Description Builds special field-to-table mappings from declarative rules. ### Method N/A (Function Signature) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `getModelName` ((model: string) => string) - Yes - Function to translate model names - `getFieldName` ((opts: {model: string; field: string}) => string) - Yes - Function to translate field names - `config` (SurrealDBAdapterConfig | undefined) - No - Optional config for debug logging ### Return Type `Record boolean; recordTable: string}>>` — Nested map of special case mappings with optional conditions. ### Description Builds a structure of special field mapping rules from `FIELD_MAPPING_RULES`. Each rule specifies a field that references a table, optionally with a condition function that checks the data. Used for non-standard reference fields like `account.accountId` which should reference `user` only when `providerId === "credential"`. ### Example ```typescript const specialCases = buildSpecialCasesMapping(getModelName, getFieldName, config); // Result structure: // { // account: { // accountId: { // recordTable: "user", // condition: (data) => data.providerId === "credential" // } // } // } ``` ``` -------------------------------- ### Not In Array Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of checking if a field's value is NOT present within a given array. Useful for excluding multiple values. ```typescript { field: "status", operator: "not_in", value: ["deleted", "banned"] } ``` -------------------------------- ### In Array Where Condition Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Example of checking if a field's value is present within a given array. Useful for multiple possible matches. ```typescript { field: "status", operator: "in", value: ["active", "pending"] } ``` -------------------------------- ### Initialize Adapter with Debug Logs for Query Count Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/errors-and-debugging.md Initialize the SurrealDB adapter with debug logs enabled to monitor the number of queries executed. Query counts can be observed in the logging handler. ```typescript let queryCount = 0; const adapter = surrealdbAdapter(db, { debugLogs: true }); // Count logs in your logging handler // Each [0/#] entry is one query ``` -------------------------------- ### String 'CONTAINS' Operator Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Filters records where the 'email' field contains the specified substring '@example.com'. Useful for partial string matching. ```typescript where: [{ field: "email", operator: "contains", value: "@example.com" }] ``` -------------------------------- ### Initialize Adapter with Selective Debug Logging for Slow Queries Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/errors-and-debugging.md Enable selective method flags in debug logs for production environments to detect slow queries. This helps in identifying performance bottlenecks in operations like findMany, count, updateMany, and deleteMany. ```typescript const adapter = surrealdbAdapter(db, { debugLogs: { findMany: true, // Find many often slow count: true, // Count can be slow updateMany: true, // Batch updates can be slow deleteMany: true, // Batch deletes can be slow } }); ``` -------------------------------- ### Adapter Methods Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Provides the signatures for the core database operations exposed by the adapter. ```APIDOC ## DatabaseAdapter Methods ### Description Interface defining the methods available for database operations. ### Methods - **create(params: { model, data, select }): Promise** - Creates a new record. - **findOne(params: { model, where, select }): Promise** - Finds a single record matching the criteria. - **findMany(params: { model, where, limit, offset, sortBy }): Promise** - Finds multiple records matching the criteria. - **count(params: { model, where }): Promise** - Counts the number of records matching the criteria. - **update(params: { model, where, update }): Promise** - Updates a single record matching the criteria. - **updateMany(params: { model, where, update }): Promise** - Updates multiple records matching the criteria. - **delete(params: { model, where }): Promise** - Deletes a single record matching the criteria. - **deleteMany(params: { model, where }): Promise** - Deletes multiple records matching the criteria. - **createSchema(params: { file, tables }): Promise** - Creates a schema based on the provided file and tables. ``` -------------------------------- ### surrealdbAdapter() Function Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/GENERATION_SUMMARY.txt The main function to create a SurrealDB adapter instance. It takes a configuration object and returns an adapter with various methods for interacting with SurrealDB. ```APIDOC ## surrealdbAdapter() ### Description Initializes and returns a SurrealDB adapter instance. This adapter provides methods for performing CRUD operations and other database interactions. ### Method `surrealdbAdapter(config: SurrealDBAdapterConfig)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (Configuration Interface: SurrealDBAdapterConfig) - **debugLogs** (boolean) - Optional - Controls whether debug logs are enabled. - **idGenerator** (IdGenerator) - Optional - Specifies the strategy for ID generation. See `types.md` for details on the 9 available strategies. - **usePlural** (boolean) - Optional - Determines if table names should be pluralized. - **allowPassingId** (boolean) - Optional - Allows passing custom IDs during record creation. ### Request Example ```javascript import { surrealdbAdapter } from 'surreal-better-auth'; const adapter = await surrealdbAdapter({ // configuration options... }); ``` ### Response #### Success Response - **adapter** (object) - An object containing the following methods: - `create(data)`: Inserts a record with ID generation. - `findOne(id)`: Selects a single record. - `findMany(ids)`: Selects multiple records with pagination. - `count(filter)`: Counts records based on a WHERE clause. - `update(id, data)`: Updates a single record. - `updateMany(ids, data)`: Updates multiple records in a batch. - `delete(id)`: Deletes a single record. - `deleteMany(ids)`: Deletes multiple records in a batch. #### Response Example ```json { "create": "function", "findOne": "function", "findMany": "function", "count": "function", "update": "function", "updateMany": "function", "delete": "function", "deleteMany": "function" } ``` ``` -------------------------------- ### Build SurrealQL Query Suffix Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-helpers.md Constructs the trailing portion of a SurrealQL query, supporting ORDER BY, LIMIT, START AT, GROUP ALL, and RETURN clauses. ```typescript export function buildQuerySuffix( options?: QuerySuffixOptions, getFieldName?: (opts: { model: string; field: string }) => string, ): string ``` ```typescript const suffix = buildQuerySuffix({ sortBy: { field: "createdAt", direction: "desc" }, limit: 10, offset: 20, model: "user", getFieldName: getFieldName, }); // Result: " ORDER BY createdAt DESC LIMIT 10 START AT 20" ``` -------------------------------- ### Execute a Query with the Adapter Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/errors-and-debugging.md Run a query using the adapter to test functionality and generate log output for debugging. ```typescript const result = await adapter.findMany({ model: "user", where: [{ field: "email", operator: "eq", value: "user@example.com" }] }); ``` -------------------------------- ### Array 'IN' Operator Example Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Filters records where the 'id' field matches any value within the provided array. This is efficient for checking against a list of possibilities. ```typescript where: [{ field: "id", operator: "in", value: ["user1", "user2", "user3"] }] ``` -------------------------------- ### Run All Tests with Bun Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/bottom.md This command executes all available tests, including unit and integration tests. ```bash bun run test:all ``` -------------------------------- ### Create SurrealDB Better Auth Adapter Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/00-START-HERE.md Instantiate the SurrealDB adapter for Better Auth. Configure ID generation strategy, debug logging, plural table names, and custom ID passing. ```typescript import { betterAuth } from "better-auth"; import { surrealdbAdapter } from "surreal-better-auth"; import Surreal from "surrealdb"; // Connect to SurrealDB const db = new Surreal(); await db.connect("ws://localhost:8000"); await db.use({ namespace: "production", database: "myapp" }); // Create auth with adapter export const auth = betterAuth({ database: surrealdbAdapter(db, { idGenerator: "surreal.UUIDv7", debugLogs: process.env.NODE_ENV === "development", usePlural: false, allowPassingId: false, }), emailAndPassword: { enabled: true }, }); ``` -------------------------------- ### Adapter Methods Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the 8 core methods provided by the SurrealDB adapter for performing CRUD operations. ```APIDOC ## Adapter Methods ### create() #### Description Inserts a new record into the database, with automatic ID generation based on the configured `idGenerator` strategy. #### Method `create(data: object)` #### Parameters - **data** (object) - The record data to insert. #### Request Example ```javascript await adapter.create({ name: 'John Doe', email: 'john@example.com' }); ``` ### findOne() #### Description Retrieves a single record from the database using its ID. Optimized for single record retrieval. #### Method `findOne(id: string | RecordId)` #### Parameters - **id** (string | RecordId) - The ID of the record to retrieve. #### Request Example ```javascript await adapter.findOne('user:john'); ``` ### findMany() #### Description Retrieves multiple records from the database, supporting pagination and filtering. #### Method `findMany(ids: string[] | RecordId[], options?: { pagination?: PaginationOptions, filter?: object })` #### Parameters - **ids** (string[] | RecordId[]) - An array of record IDs to retrieve. - **options** (object) - Optional. Includes pagination and filter options. - **pagination** (object) - Pagination settings (e.g., limit, offset). - **filter** (object) - Filtering criteria. #### Request Example ```javascript await adapter.findMany(['user:john', 'user:jane'], { pagination: { limit: 10, offset: 0 }, filter: { active: true } }); ``` ### count() #### Description Counts the number of records that match a given filter criteria. #### Method `count(filter: object)` #### Parameters - **filter** (object) - The criteria to filter records by. #### Request Example ```javascript await adapter.count({ status: 'active' }); ``` ### update() #### Description Updates a single existing record in the database. #### Method `update(id: string | RecordId, data: object)` #### Parameters - **id** (string | RecordId) - The ID of the record to update. - **data** (object) - The updated data for the record. #### Request Example ```javascript await adapter.update('user:john', { email: 'john.doe.updated@example.com' }); ``` ### updateMany() #### Description Updates multiple records in a single batch operation. #### Method `updateMany(ids: string[] | RecordId[], data: object)` #### Parameters - **ids** (string[] | RecordId[]) - An array of record IDs to update. - **data** (object) - The updated data to apply to each record. #### Request Example ```javascript await adapter.updateMany(['user:john', 'user:jane'], { status: 'inactive' }); ``` ### delete() #### Description Deletes a single record from the database by its ID. #### Method `delete(id: string | RecordId)` #### Parameters - **id** (string | RecordId) - The ID of the record to delete. #### Request Example ```javascript await adapter.delete('user:john'); ``` ### deleteMany() #### Description Deletes multiple records from the database in a single batch operation. #### Method `deleteMany(ids: string[] | RecordId[])` #### Parameters - **ids** (string[] | RecordId[]) - An array of record IDs to delete. #### Request Example ```javascript await adapter.deleteMany(['user:john', 'user:jane']); ``` ``` -------------------------------- ### Batch Update Sessions Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Update multiple session records in a single operation, for example, to deactivate sessions for a specific user. This pattern is efficient for bulk modifications. ```typescript const updated = await adapter.updateMany({ model: "session", where: [{ field: "userId", operator: "eq", value: "user:abc123" }], update: { active: false } }); ``` ```surql UPDATE session MERGE { active: false } WHERE userId = user:abc123 ``` -------------------------------- ### surrealdbAdapter() Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-adapter.md Creates and returns a configured Better Auth adapter for SurrealDB. It accepts an active SurrealDB connection instance and optional configuration options. ```APIDOC ## Function: surrealdbAdapter ### Description Creates and returns a configured Better Auth adapter for SurrealDB. This function accepts a SurrealDB connection and optional configuration, returning an adapter object compatible with Better Auth's `betterAuth()` configuration. The adapter intercepts all database operations and translates them to optimized SurrealDB queries with record link support. ### Signature ```typescript export const surrealdbAdapter = ( db: Surreal, config?: SurrealDBAdapterConfig, ) => DatabaseAdapter ``` ### Parameters #### Parameters - **db** (`Surreal`) - Required - Active SurrealDB connection instance - **config** (`SurrealDBAdapterConfig`) - Optional - Adapter configuration options ### Return Type `DatabaseAdapter` — A fully configured Better Auth database adapter that implements all CRUD operations for SurrealDB. ### Throws/Rejects No errors thrown directly. Invalid `idGenerator` values in config throw when IDs are generated. ### Example ```typescript import { betterAuth } from "better-auth"; import { surrealdbAdapter } from "surreal-better-auth"; import Surreal from "surrealdb"; // Initialize SurrealDB connection const db = new Surreal(); await db.connect("ws://localhost:8000"); await db.use({ namespace: "production", database: "myapp" }); // Create auth instance export const auth = betterAuth({ database: surrealdbAdapter(db, { idGenerator: "surreal.UUIDv4", debugLogs: true, }), emailAndPassword: { enabled: true, }, }); ``` ``` -------------------------------- ### Count Records with SurrealDB Adapter Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-adapter.md Count the number of records that match the specified WHERE conditions. This method is useful for getting aggregate information without fetching the records themselves. ```typescript async count({ model, where }: { model: string; where?: Where[]; }): Promise ``` ```typescript const verifiedCount = await adapter.count({ model: "user", where: [{ field: "emailVerified", operator: "eq", value: true }], }); ``` -------------------------------- ### Advanced Authentication Configuration Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/README.md Configure the better-auth instance with the surrealdbAdapter, enabling debug logs, custom ID generation, and social providers like GitHub and Google. Ensure environment variables for client IDs and secrets are set. ```typescript // lib/auth.ts import { betterAuth } from "better-auth"; import { surrealdbAdapter } from "surreal-better-auth"; import { db } from "./db"; export const auth = betterAuth({ database: surrealdbAdapter(db, { // Enable debug logging debugLogs: true, // Let SurrealDB generate ULID idGenerator: "surreal.ULID", // Use singular table names usePlural: false, // Allow passing custom IDs allowPassingId: true, }), emailAndPassword: { enabled: true, requireEmailVerification: true, }, socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }, }, plugins: [ // Add any better-auth plugins here and configure them as usual. ], }); ``` -------------------------------- ### Configuration Type Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Defines the optional configuration settings available when initializing the SurrealDB adapter. ```APIDOC ## SurrealDBAdapterConfig ### Description Configuration options for the SurrealDB adapter. ### Properties - **debugLogs** (boolean | AdapterDebugLogs) - Optional - Enables or configures debug logging. - **idGenerator** (IdGenerator) - Optional - Specifies the strategy for generating record IDs. - **usePlural** (boolean) - Optional - Determines if table names should be pluralized. - **allowPassingId** (boolean) - Optional - Allows passing an ID directly during record creation. ``` -------------------------------- ### Configure Invalid ID Generator Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/errors-and-debugging.md This example demonstrates an invalid configuration for the `idGenerator` option. The provided string must match one of the supported `IdGenerator` union types. ```typescript const adapter = surrealdbAdapter(db, { idGenerator: "invalid.generator" // Not in IdGenerator union type }); ``` -------------------------------- ### TypeScript Model Name Type Checking Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Ensures that model names used in queries are valid according to the schema. Requires additional setup for full type safety. ```typescript const user = await adapter.findOne({ model: "user", // TypeScript knows valid model names where: [...], }); ``` -------------------------------- ### create() Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-adapter.md Creates a single record in the database. It automatically generates an ID and returns the created record, optionally selecting specific fields. ```APIDOC ## create() ### Description Creates a new record with automatic ID generation. If `select` is provided, only those fields are returned. The id field is always included in the return value. ### Method `create({ model, data, select }: { model: string; data: Record; select?: string[]; })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model** (string) - Required - Better Auth internal model name - **data** (Record) - Required - Field values for the new record - **select** (string[]) - Optional - Fields to return in response ### Request Example ```typescript const newUser = await adapter.create({ model: "user", data: { email: "user@example.com", name: "John Doe", emailVerified: false, }, select: ["id", "email", "name"], }); ``` ### Response #### Success Response (200) - **any** - The created record with all fields as specified by Better Auth schema, with IDs converted to strings. #### Response Example ```json { "id": "user:generated_id", "email": "user@example.com", "name": "John Doe" } ``` ``` -------------------------------- ### Configure Surreal-Better-Auth with Advanced Options Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/packages/surreal-better-auth/README.md Configure the Surreal-Better-Auth instance with advanced database adapter settings and social providers. Ensure environment variables for client IDs and secrets are set. ```typescript import { betterAuth, surrealdbAdapter } from "surreal-better-auth"; import { db } from "./db"; export const auth = betterAuth({ database: surrealdbAdapter(db, { // Enable debug logging debugLogs: true, // Let SurrealDB generate ULID idGenerator: "surreal.ULID", // Use singular table names usePlural: false, // Allow passing custom IDs allowPassingId: true, }), emailAndPassword: { enabled: true, requireEmailVerification: true, }, socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }, }, plugins: [ // Add any better-auth plugins here and configure them as usual. ], }); ``` -------------------------------- ### Integrating SurrealDB Adapter with Better Auth Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/types.md Shows how to pass the SurrealDB adapter configuration to the `betterAuth` function via the `database` option. ```typescript export const auth = betterAuth({ database: surrealdbAdapter(db, { debugLogs: true, idGenerator: "surreal.UUIDv4", usePlural: false, allowPassingId: false, }), // ... other Better Auth config }); ``` -------------------------------- ### SurrealDB Better Auth Source File Structure Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/INDEX.md Illustrates the directory structure of the 'surreal-better-auth' package source code. This helps in understanding the organization of different modules within the library. ```tree ├── index.ts # Main exports ├── surreal-adapter.ts # Adapter implementation ├── helpers.ts # Helper functions ├── schema.ts # Schema generation └── types.ts # Type definitions ``` -------------------------------- ### Run All Tests Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/examples/sk/README.md Ensures SurrealDB is running and then executes all defined tests. ```bash # Run tests: bun run test:all ``` -------------------------------- ### buildQuerySuffix() Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-helpers.md Builds the trailing portion of a SurrealQL query, including ORDER BY, LIMIT, OFFSET, GROUP ALL, and RETURN clauses. ```APIDOC ## buildQuerySuffix() ### Description Builds query suffix with ORDER BY, LIMIT, OFFSET, GROUP ALL, and RETURN clauses. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```typescript export function buildQuerySuffix( options?: QuerySuffixOptions, getFieldName?: (opts: { model: string; field: string }) => string, ): string ``` ### Return Type `string` — SurrealQL suffix string (may be empty string if no options). ### Example ```typescript const suffix = buildQuerySuffix({ sortBy: { field: "createdAt", direction: "desc" }, limit: 10, offset: 20, model: "user", getFieldName: getFieldName, }); // Result: " ORDER BY createdAt DESC LIMIT 10 START AT 20" ``` ``` -------------------------------- ### Create a Record with SurrealDB Adapter Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/api-reference-adapter.md Use this method to create a new record in the database. Specify the model, data, and optionally which fields to select in the response. The ID is automatically generated. ```typescript async create({ model, data, select }: { model: string; data: Record; select?: string[]; }): Promise ``` ```typescript const newUser = await adapter.create({ model: "user", data: { email: "user@example.com", name: "John Doe", emailVerified: false, }, select: ["id", "email", "name"], }); ``` -------------------------------- ### Run Specific Test File Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/CONTRIBUTING.md Execute tests for a specific file within the adapter's test suite. Useful for targeted debugging. ```bash # Run specific test file bun vitest packages/surreal-better-auth/tests/adapter.test.ts ``` -------------------------------- ### SurrealDB Adapter Configuration (Production) Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Configure the SurrealDB adapter for production with debug logs disabled. ```typescript const adapter = surrealdbAdapter(db, { debugLogs: false, idGenerator: "surreal.UUIDv7", usePlural: false, allowPassingId: false, }); ``` -------------------------------- ### Format Record Link References Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Demonstrates how foreign key fields are automatically converted to SurrealDB record links, accepting string IDs and storing them as `RecordId` objects. ```typescript // Input: string ID // { userId: "abc123" } // Stored as: RecordId // { userId: RecordId("user", "abc123") } // Output: string format // { userId: "user:abc123" } ``` -------------------------------- ### Basic CREATE Operation Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/querying-patterns.md Creates a new record in the specified model with provided data. The 'select' option allows specifying which fields to return. ```typescript const result = await adapter.create({ model: "user", data: { email: "user@example.com", name: "John Doe", emailVerified: false, createdAt: new Date(), }, select: ["id", "email", "name"] }); // Returns: { id: "user:...", email: "...", name: "..." } ``` ```surql CREATE type::thing('user', rand::uuid::v7()) CONTENT { email: "user@example.com", name: "John Doe", emailVerified: false, createdAt: 2024-01-15T10:30:45Z } RETURN id, email, name ``` -------------------------------- ### Minimal SurrealDB Adapter Configuration Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/configuration.md Uses default settings for the SurrealDB adapter. Defaults include debugLogs: false, undefined idGenerator, usePlural: false, and allowPassingId: false. ```typescript const adapter = surrealdbAdapter(db); // Uses defaults: // - debugLogs: false // - idGenerator: undefined (Better Auth default) // - usePlural: false (singular table names) // - allowPassingId: false (no custom IDs) ``` -------------------------------- ### SurrealDB Database Adapter Methods Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/README.md Defines the interface for the database adapter, outlining methods for CRUD operations, schema creation, and more. ```typescript interface DatabaseAdapter { create(params: { model, data, select }): Promise findOne(params: { model, where, select }): Promise findMany(params: { model, where, limit, offset, sortBy }): Promise count(params: { model, where }): Promise update(params: { model, where, update }): Promise updateMany(params: { model, where, update }): Promise delete(params: { model, where }): Promise deleteMany(params: { model, where }): Promise createSchema(params: { file, tables }): Promise } ``` -------------------------------- ### Environment-Based SurrealDB Adapter Configuration Source: https://github.com/oskar-gmerek/surreal-better-auth/blob/main/_autodocs/configuration.md Configure the SurrealDB adapter using environment variables for dynamic settings like debug logs, ID generation, and table naming conventions. This approach is useful for managing different configurations across environments. ```typescript const adapterConfig = { debugLogs: process.env.NODE_ENV === "development" || process.env.DEBUG === "true", idGenerator: (process.env.ID_GENERATOR as any) || "surreal.UUIDv7", usePlural: process.env.USE_PLURAL_TABLES === "true", allowPassingId: process.env.ALLOW_CUSTOM_IDS === "true", }; const adapter = surrealdbAdapter(db, adapterConfig); ```