1.1.1 • Published 1 year ago
@brahimemo/surrealdb-js v1.1.1
# @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-jsUsage
This package provides a simple interface for querying a SurrealDB database.
Initialization
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: Requiresusernameandpassword. Optionally includesnamespaceanddatabase(ForNamespaceOrDatabaseUser).Token: Requires atoken.Scope: Requires ascopeandvars(key-value pairs).Anonymous: Auth === undefined.
Querying the Database
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 beforeThe query method returns a QueryResult which is a tuple:
[RequestResult<T>[], ErrorResponse?]
RequestResult<T>[]: An array ofRequestResultobjects. Each object contains the query result (result), status (OKorERR), and timestamp (time). If the query is successful,resultwill 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.
Authentication
To authenticate, use the authenticate method:
db.authenticate({
method: 'Token',
token: '<your token>'
});To invalidate the current authentication, use:
db.invalidate();Error Handling
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.
Versioning
Specify the SurrealDB version using the version option in the constructor (1.x <= or >= 2.x). The default is >= 2.x.
License
MIT