# @brahimemo/surrealdb-js
A lightweight and efficient JavaScript client for interacting with SurrealDB databases. Supports both v1.x and v2.x+.
## Installation
```bash
npm i @brahimemo/surrealdb-js
This package provides a simple interface for querying a SurrealDB database.
First, initialize the SurrealDB
class with your database configuration:
import SurrealDB from '@brahimemo/surrealdb-js';
const db = new SurrealDB({
url: 'http://localhost:8000', // Your SurrealDB URL
version: '>= 2.x', // Specify the SurrealDB version (1.x <= or >= 2.x)
namespace: '<your namespace>',
database: '<your database>',
auth: { // Authentication details (optional)
method: 'Root',
vars: {
username: '<your username>',
password: '<your password>'
}
}
});
Supported authentication methods:
-
Root
: Requiresusername
andpassword
. Optionally includesnamespace
anddatabase
(ForNamespace
OrDatabase
User). -
Token
: Requires atoken
. -
Scope
: Requires ascope
andvars
(key-value pairs). -
Anonymous
: Auth === undefined.
Use the query
method to execute SQL queries:
type User = {
id: string;
name: string;
}
const [data, error] = await db.query<User[]>(`SELECT * FROM users`);
// Handle the result (see below)
if (error === nil && data[0].status === "OK") {
console.log(data); // Access the query results
} else {
console.error(error); // Access the error response
}
//Example with variables
type User = {
id: string;
name: string;
}
const [data, error] = await db.query<User[]>(`SELECT * FROM users WHERE name = $name;`, {name: 'John Doe'});
//Handle result the same way as before
The query
method returns a QueryResult
which is a tuple:
[RequestResult<T>[], ErrorResponse?]
-
RequestResult<T>[]
: An array ofRequestResult
objects. Each object contains the query result (result
), status (OK
orERR
), and timestamp (time
). If the query is successful,result
will contain the data; otherwise, it will benull
. -
ErrorResponse
: If there is an error, this will contain the error message. If the query is successful, this will benull
.
To authenticate, use the authenticate
method:
db.authenticate({
method: 'Token',
token: '<your token>'
});
To invalidate the current authentication, use:
db.invalidate();
The query
method returns a tuple. Check the status to determine success or failure. Error messages are provided in the second element of the tuple.
Specify the SurrealDB version using the version
option in the constructor (1.x <=
or >= 2.x
). The default is >= 2.x
.
MIT