nuxt-surrealdb
Version:
A Nuxt module aimed to simplify the use of SurrealDB
188 lines (187 loc) • 8.82 kB
TypeScript
import type { Surreal, RecordResult, Jsonify, AnyRecordId, RecordIdRange, Table, Duration, DateTime, ExprLike, VersionInfo, SqlExportOptions } from 'surrealdb';
import type { AsyncData, AsyncDataOptions, KeysOf, PickFrom } from '#app/composables/asyncData';
import type { NuxtError } from '#app';
import { type MaybeRefOrGetter } from '#imports';
import type { MaybePromise } from '../../types/index.js';
type Field<I> = keyof I | (string & {});
type Collect<T extends unknown[]> = T extends [] ? unknown[] : {
[K in keyof T]: Jsonify<T[K]>;
};
export type SurrealAsyncData<DataT, ErrorT> = AsyncData<DataT, ErrorT>;
export type SurrealAsyncDataOptions<T, DefaultT> = AsyncDataOptions<T, T, KeysOf<T>, DefaultT>;
export type UseSurrealAsyncData<T, ErrorT, DefaultT> = SurrealAsyncData<PickFrom<T, KeysOf<T>> | DefaultT, (ErrorT extends Error | NuxtError ? ErrorT : NuxtError<ErrorT>) | undefined>;
/**
* SSR-safe composable for executing arbitrary SurrealDB operations.
*
* @param cb - Callback receiving the connected {@link Surreal} client
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* const { data } = await useSurrealAsyncData((client) => {
* return client.select(new Table('users')).json()
* })
* ```
*/
export declare function useSurrealAsyncData<T, ErrorT, DefaultT = undefined>(cb: (client: Surreal) => MaybePromise<T>, asyncDataOptions?: SurrealAsyncDataOptions<T, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<T, ErrorT, DefaultT>>;
/**
* Returns the record of the currently authenticated user.
* Selects the `$auth` parameter from SurrealDB.
*
* Make sure the user has permission to select their own record,
* otherwise an empty result is returned.
*
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* const { data: user } = await useSurrealAuth<{ name: string }>()
* ```
*/
export declare function useSurrealAuth<T, ErrorT, DefaultT = undefined>(asyncDataOptions?: SurrealAsyncDataOptions<Jsonify<RecordResult<T> | undefined>, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<Jsonify<RecordResult<T> | undefined>, ErrorT, DefaultT>>;
/**
* Export the database as a SurrealQL string.
*
* @param expOptions - Export options (reactive)
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* const { data: dump } = await useSurrealExport()
* ```
*/
export declare function useSurrealExport<ErrorT, DefaultT = undefined>(expOptions?: MaybeRefOrGetter<Partial<SqlExportOptions>>, asyncDataOptions?: SurrealAsyncDataOptions<string, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<string, ErrorT, DefaultT>>;
/**
* Import SurrealQL data into the database.
*
* @param input - The SurrealQL string to import (reactive)
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* const { data: ok } = await useSurrealImport('DEFINE TABLE users;')
* ```
*/
export declare function useSurrealImport<ErrorT, DefaultT = undefined>(input: MaybeRefOrGetter<string>, asyncDataOptions?: SurrealAsyncDataOptions<true, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<true, ErrorT, DefaultT>>;
/**
* Run a set of SurrealQL statements against the database.
* Results are automatically JSON-serialized for SSR payload transfer.
*
* @param query - The SurrealQL query string (reactive)
* @param bindings - Optional query variable bindings (reactive)
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* const { data } = await useSurrealQuery<[User[]]>(
* 'SELECT * FROM users WHERE age > $min',
* { min: 18 },
* )
* ```
*/
export declare function useSurrealQuery<T extends unknown[], ErrorT, DefaultT = undefined>(query: MaybeRefOrGetter<string>, bindings?: MaybeRefOrGetter<Record<string, MaybeRefOrGetter<unknown>>>, asyncDataOptions?: SurrealAsyncDataOptions<Collect<T>, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<Collect<T>, ErrorT, DefaultT>>;
/**
* Run a SurrealQL function and return the result.
*
* @param name - The full name of the function to run (reactive)
* @param args - Arguments supplied to the function (reactive)
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* const { data } = await useSurrealRun<number>('fn::get_count', ['users'])
* ```
*/
export declare function useSurrealRun<T, ErrorT, DefaultT = undefined>(name: MaybeRefOrGetter<string>, args?: MaybeRefOrGetter<unknown[]>, asyncDataOptions?: SurrealAsyncDataOptions<Jsonify<T>, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<Jsonify<T>, ErrorT, DefaultT>>;
/**
* Structural interface matching the upstream `SelectPromise`'s chainable API.
* Since `SelectPromise` is not exported from `surrealdb`, this provides
* equivalent type support through structural compatibility.
*/
export interface SurrealSelectBuilder<T, I> {
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* @remarks Called internally by the composable — you do not need to call this yourself.
*/
json(): PromiseLike<Jsonify<T>>;
/**
* Configure the query to only select the specified field(s)
*/
fields(...fields: Field<I>[]): SurrealSelectBuilder<T, I>;
/**
* Configure the query to retrieve the value of the specified field
*/
value(field: Field<I>): SurrealSelectBuilder<T, I>;
/**
* Configure the query to start at the specified index
*/
start(start: number): SurrealSelectBuilder<T, I>;
/**
* Configure the query to limit the number of results
*/
limit(limit: number): SurrealSelectBuilder<T, I>;
/**
* Configure the query to fetch only records that match the condition.
*
* Expressions can be imported from the `surrealdb` package and combined
* to compose the desired condition.
*
* @see {@link https://github.com/surrealdb/surrealdb.js/blob/main/packages/sdk/src/utils/expr.ts}
*/
where(expr: ExprLike): SurrealSelectBuilder<T, I>;
/**
* Configure the query to fetch record link contents for the specified field(s)
*/
fetch(...fields: Field<I>[]): SurrealSelectBuilder<T, I>;
/**
* Configure the timeout of the query
*/
timeout(timeout: Duration): SurrealSelectBuilder<T, I>;
/**
* Configure a custom version of the data being created. This is used
* alongside version enabled storage engines such as SurrealKV.
*/
version(version: DateTime): SurrealSelectBuilder<T, I>;
}
export type UseSurrealSelectPromise<T, I> = (builder: SurrealSelectBuilder<T, I>) => SurrealSelectBuilder<T, I>;
/**
* Select records from a table, record ID, or record ID range.
* Accepts a chainable builder callback for filtering, pagination, and field selection.
* Results are automatically JSON-serialized. The first argument supports reactive inputs.
*
* @param tableOrRecord - The table, record ID, or range to select from (reactive)
* @param select - Optional callback to configure the select query via the builder API
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* // Select all records from a table
* const { data } = await useSurrealSelect(new Table('users'))
*
* // With filtering and pagination
* const { data } = await useSurrealSelect(
* new Table('users'),
* q => q.where(eq('active', true)).limit(10).start(0),
* )
*
* // Select a single record
* const id = ref<string>('tobie')
* const { data } = await useSurrealSelect(() => new RecordId('users', id.value))
* ```
*/
export declare function useSurrealSelect<T, ErrorT, DefaultT = undefined>(tableOrRecord: MaybeRefOrGetter<AnyRecordId>, select?: UseSurrealSelectPromise<RecordResult<T> | undefined, T>, asyncDataOptions?: SurrealAsyncDataOptions<Jsonify<RecordResult<T> | undefined>, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<Jsonify<RecordResult<T> | undefined>, ErrorT, DefaultT>>;
export declare function useSurrealSelect<T, ErrorT, DefaultT = undefined>(tableOrRecord: MaybeRefOrGetter<Table | RecordIdRange>, select?: UseSurrealSelectPromise<RecordResult<T>[], T>, asyncDataOptions?: SurrealAsyncDataOptions<Jsonify<RecordResult<T>[]>, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<Jsonify<RecordResult<T>[]>, ErrorT, DefaultT>>;
/**
* Returns the version information of the connected SurrealDB server.
*
* @param asyncDataOptions - Options passed to `useAsyncData`
*
* @example
* ```ts
* const { data: version } = await useSurrealVersion()
* ```
*/
export declare function useSurrealVersion<ErrorT, DefaultT = undefined>(asyncDataOptions?: SurrealAsyncDataOptions<VersionInfo, DefaultT>, _key?: string): Promise<UseSurrealAsyncData<VersionInfo, ErrorT, DefaultT>>;
export {};