Skip to main content

API Reference

Complete Lovrabet SDK API reference documentation, including detailed descriptions of all classes and methods.

Core Architecture

The Lovrabet SDK uses a modular architecture design, consisting of the following core components:

LovrabetClient (Client)
├── models (Model Accessor) -> ModelManager (Model Manager)
├── AuthManager (Authentication Manager)
└── HttpClient (HTTP Client)
├── AuthManager (Dependency)
└── ErrorHandler (Error Handler)

ModelManager (Model Manager)
└── BaseModel[] (Model Instance Cache)
└── HttpClient (Dependency)

Core Type Definitions

ModelConfig

Single model configuration:

interface ModelConfig {
tableName: string; // Data table name (required)
datasetCode: string; // Dataset code (required, unique identifier)
name?: string; // Display name (optional, for UI display)
alias?: string; // Alias (optional, for client.models.alias access)
dbName?: string; // Database name (optional, for distinguishing different databases)
}

ModelsConfig

Model collection configuration (supports both array and object formats):

interface ModelsConfig {
appCode: string; // App Code
models: ModelConfig[] | Record<string, ModelConfig>; // Model configuration (array or object format)
}

Array format (recommended):

const config: ModelsConfig = {
appCode: "my-app",
models: [
{ datasetCode: "xxx", tableName: "users", alias: "users" },
{ datasetCode: "yyy", tableName: "orders", alias: "orders" },
],
};

Object format (backward compatible):

const config: ModelsConfig = {
appCode: "my-app",
models: {
Users: { datasetCode: "xxx", tableName: "users" },
Orders: { datasetCode: "yyy", tableName: "orders" },
},
};

ClientConfig

Complete client configuration:

interface ClientConfig {
// Basic configuration
appCode?: string; // App Code
serverUrl?: string; // Server URL
env?: Environment; // Runtime environment

// Authentication configuration
token?: string; // User token (Bearer authentication)
timestamp?: number; // Timestamp paired with token (required for OpenAPI mode)
accessKey?: string; // OpenAPI AccessKey (Signature authentication)
secretKey?: string; // OpenAPI SecretKey (Signature authentication)
requiresAuth?: boolean; // Whether authentication is required, default true

// Model configuration
models?: ModelConfig[] | Record<string, ModelConfig>; // Model configuration
apiConfigName?: string; // Reference to a registered configuration name

// Extended options
options?: {
timeout?: number; // Request timeout in milliseconds
retryCount?: number; // Number of retries
debug?: boolean; // Debug mode, print request details (v1.1.14+)
onError?: (error: any) => void; // Error callback
onRedirectToLogin?: () => void; // Login redirect callback
};
}

ListParams

List query parameters:

interface ListParams {
currentPage?: number; // Current page number (default: 1)
pageSize?: number; // Page size (default: 20)
[key: string]: any; // Other query parameters
}

ListResponse

Paginated response format:

interface ListResponse<T> {
tableData: T[]; // Data list
total: number; // Total record count
currentPage: number; // Current page number
pageSize: number; // Page size
}

SortOrder v1.1.16+

Sort direction enum:

enum SortOrder {
ASC = "asc", // Ascending
DESC = "desc", // Descending
}

Usage example:

import { SortOrder } from "@lovrabet/sdk";

// Using enum values (recommended)
const sortList = [{ createTime: SortOrder.DESC }, { name: SortOrder.ASC }];

// Or use strings directly
const sortList = [{ createTime: "desc" }, { name: "asc" }];

SortList v1.1.16+

Sort configuration list type:

type SortList = Record<string, "asc" | "desc">[];

The sort list uses a concise key-value format, where each object represents a sort field:

  • key: Field name
  • value: Sort direction ("asc" or "desc")

Usage example:

import { SortOrder, type SortList } from "@lovrabet/sdk";

// Single field sort
const sort1: SortList = [{ id: SortOrder.DESC }];

// Multi-field sort
const sort2: SortList = [
{ priority: SortOrder.DESC }, // First priority: sort by priority descending
{ createTime: SortOrder.DESC }, // Second priority: sort by creation time descending
{ name: SortOrder.ASC }, // Third priority: sort by name ascending
];

// Using sorting
const users = await client.models.users.filter(
{ currentPage: 1, pageSize: 20 },
sort2
);

SelectOption v1.1.18+

Dropdown option data format:

interface SelectOption {
label: string; // Display text
value: string; // Option value
}

This is the standard format returned by the getSelectOptions() method, which can be used directly in frontend components:

const options: SelectOption[] = [
{ label: "Zhang San", value: "user001" },
{ label: "Li Si", value: "user002" },
];

// Use in React Select component
<Select>
{options.map((opt) => (
<Option key={opt.value} value={opt.value}>
{opt.label}
</Option>
))}
</Select>;

SelectOptionsParams v1.1.18+

Dropdown option query parameters:

interface SelectOptionsParams {
code: string; // Field name used as option value
label: string; // Field name used as display text
}

Usage example:

// Get dropdown options from the users table
const params: SelectOptionsParams = {
code: "user_id", // The user_id field of the data table as value
label: "user_name", // The user_name field of the data table as label
};

const options = await client.models.users.getSelectOptions(params);
// Returns: [{ label: 'Zhang San', value: 'user001' }, ...]

// Use in order status selection
const statusParams: SelectOptionsParams = {
code: "status_code",
label: "status_name",
};
const statusOptions = await client.models.orderStatus.getSelectOptions(
statusParams
);

Factory Functions

createClient()

Creates an SDK client instance, supporting multiple configuration methods.

Function Signature

function createClient(
config?: Partial<ClientConfig> | ModelsConfig | string
): LovrabetClient;

Parameters

ParameterTypeDefaultDescription
configPartial<ClientConfig> | ModelsConfig | string'default'Client configuration

Usage Methods

1. Use a pre-registered configuration name

const client = createClient("default");
const prodClient = createClient("prod");

2. Pass model configuration directly

const client = createClient({
appCode: "my-app",
models: {
Users: { tableName: "users", datasetCode: "user-id" },
Posts: { tableName: "posts", datasetCode: "post-id" },
},
});

3. Use complete client configuration

const client = createClient({
appCode: "my-app",
token: "your-token",
models: {
users: { tableName: "users", datasetCode: "8d2dcbae08b54bdd84c00be558ed48df" },
},
options: {
timeout: 30000,
retryCount: 3,
},
});

4. Reference configuration but override some options

const client = createClient({
apiConfigName: "default", // Use pre-registered default configuration
token: "custom-token", // But use a custom token
});

Return Value

Returns a LovrabetClient instance.

LovrabetClient Class

The main SDK client class, providing model access and configuration management features.

Client Object Structure

const client = createClient({
appCode: "your-app-code",
accessKey: process.env.LOVRABET_ACCESS_KEY,
models: [
{ tableName: "users", datasetCode: "xxx", alias: "users" },
],
});

// client contains the following namespaces:
client.models // Model accessor
client.sql // SQL client (v1.1.19+)
client.bff // BFF client (v1.2.0+)
client.user // User client
client.api // API namespace (alias, backward compatible)

Properties

models

Model accessor, supports two access methods:

public models: { [modelName: string]: BaseModelMethods }

Access Methods:

// Standard method (recommended) - use dataset_ prefix + datasetCode
const data1 = await client.models.dataset_xxx.filter();

// Alias method (syntactic sugar) - use configured alias
const data2 = await client.models.users.filter();

sql v1.1.19+

SQL client for executing registered custom SQL queries:

public readonly sql: SqlClient

API Methods:

MethodDescription
execute({ sqlCode, params })Execute SQL query (object parameters, recommended)
execute(sqlCode, params)Execute SQL query (direct parameters, compatible)

Usage Example:

// Recommended: object parameters
const result = await client.sql.execute({
sqlCode: 'fc8e7777-06e3847d',
params: { userId: '123' }
});

// Compatible: direct parameters
const result = await client.sql.execute('fc8e7777-06e3847d', { userId: '123' });

// Alias method (backward compatible, not recommended)
const result = await client.api.executeSql('fc8e7777-06e3847d', { userId: '123' });

// Check execution result
if (result.execSuccess && result.execResult) {
result.execResult.forEach(row => console.log(row));
}

Return Type:

interface SqlExecuteResult<T> {
execSuccess: boolean; // Whether SQL execution was successful
execResult?: T[]; // Query result array
}

bff v1.2.0+

BFF client for calling Backend For Frontend endpoints:

public readonly bff: BffClient

API Methods:

MethodDescription
execute({ scriptName, params, options })Call backend function

Usage Example:

// Call without parameters
const result = await client.bff.execute({
scriptName: 'getUserDashboard'
});

// Call with parameters
const result = await client.bff.execute({
scriptName: 'calculatePrice',
params: { productId: '123', quantity: 10 }
});

// With type hints
interface DashboardData {
userCount: number;
orderCount: number;
}
const dashboard = await client.bff.execute<DashboardData>({
scriptName: 'getUserDashboard'
});

// Alias method (backward compatible, not recommended)
const result = await client.api.bff('calculatePrice', {
productId: '123',
quantity: 10
});

Return Value: Directly returns business data (already extracted from the data field in the SDK)

Error Handling: HTTP errors throw LovrabetError

user

User client for getting user information:

public readonly user: UserClient

API Methods:

MethodDescription
getList()Get user list

Usage Example:

const userList = await client.user.getList();
console.log(userList);

api

API namespace, providing backward-compatible alias access methods:

public readonly api: ApiNamespace

Recommended Methods vs Aliases:

RecommendedAlias (Compatible)
client.sql.execute()client.api.executeSql()
client.bff.execute()client.api.bff()
client.user.getList()client.api.getUserList()
Development Tip

It is recommended to use the client.sql, client.bff, and client.user namespaces for clearer code and better type hints.

Methods

setToken()

Sets the user authentication token.

setToken(token: string, timestamp?: number): void

Parameters:

  • token - User authentication token
  • timestamp - Timestamp paired with the token (optional, required for OpenAPI mode)

Usage Example:

// WebAPI mode (Cookie authentication)
client.setToken("your-new-token");

// OpenAPI mode (requires timestamp)
client.setToken("your-new-token", Date.now());

getConfig()

Gets client configuration information.

getConfig(): ClientConfig

Return Value:

  • Returns the current client configuration object

Usage Example:

const config = client.getConfig();
console.log("App Code:", config.appCode);

getBaseUrl()

Gets the API base URL.

getBaseUrl(): string

Return Value:

  • Returns the complete API base URL

Usage Example:

const baseUrl = client.getBaseUrl();
// Output: https://api.lovrabet.com/api

getModelList()

Gets the list of all available model names.

getModelList(): string[]

Return Value:

  • Returns an array of model names

Usage Example:

const modelNames = client.getModelList();
console.log("Available models:", modelNames);
// Output: ['Users', 'Posts', 'Comments']

getModel()

Gets a model instance by index or name.

getModel(indexOrName: number | string): BaseModelMethods

Parameters:

  • indexOrName - Model index (starting from 0) or model name

Return Value:

  • Returns a BaseModel instance

Usage Example:

// Get the first model by index
const firstModel = client.getModel(0);
const data = await firstModel.filter();

// Get model by name
const userModel = client.getModel("Users");
const user = await userModel.getOne(123);

BaseModel Class

The base class for all data models, providing a complete CRUD operation interface.

Methods

getList()

Gets a data list, supporting paginated queries and multi-field sorting.

async getList<T = any>(
params?: ListParams,
sortList?: SortList
): Promise<ListResponse<T>>

Parameters:

  • params - Query parameters (optional)
  • sortList - Sort configuration list (optional), supports multi-field sorting

Return Value:

  • Returns paginated data response

Usage Example:

import { SortOrder } from "@lovrabet/sdk";

// Basic query
const response = await client.models.users.filter();

// Paginated query
const response = await client.models.users.filter({
currentPage: 2,
pageSize: 50,
});

// Conditional query
const response = await client.models.users.filter({
currentPage: 1,
pageSize: 20,
name: "John", // Custom query condition
status: "active",
});

// Sorted query (single field)
const response = await client.models.users.filter(
{ currentPage: 1, pageSize: 20 },
[{ createTime: SortOrder.DESC }] // Sort by creation time descending
);

// Sorted query (multi-field)
const response = await client.models.products.filter(
{ currentPage: 1, pageSize: 20 },
[
{ priority: SortOrder.DESC }, // First by priority descending
{ createTime: SortOrder.DESC }, // Then by creation time descending
{ name: SortOrder.ASC }, // Finally by name ascending
]
);

console.log("User list:", response.tableData);
console.log("Total:", response.total);
console.log("Current page:", response.currentPage);

filter() v1.1.21+

Advanced filter query method, supporting complex conditions, field selection, sorting, and pagination (recommended to use).

async filter<T = any>(params?: FilterParams): Promise<ListResponse<T>>

Parameters:

  • params - Filter query parameters (optional)
    • where - Query conditions, supports $eq, $ne, $gte, $lte, $in, $contain and other operators
    • select - List of fields to return
    • orderBy - Sort rules
    • currentPage - Current page number
    • pageSize - Page size

Return Value:

  • Returns paginated data response

Quick Example:

import { SortOrder } from "@lovrabet/sdk";

// Complex conditional query
const response = await client.models.users.filter({
where: {
$and: [
{ age: { $gte: 18, $lte: 45 } }, // Age range
{ country: { $in: ['China', 'USA'] } }, // Country list
{ name: { $contain: 'hello' } } // Name contains
]
},
select: ['id', 'name', 'age', 'country'], // Only return these fields
orderBy: [{ createTime: SortOrder.DESC }], // Sort by creation time descending
currentPage: 1,
pageSize: 20
});
Detailed Usage Guide

The filter API provides powerful query capabilities, supporting all condition operators ($eq, $ne, $gte, $lte, $in, $contain, $startWith, $endWith) and logical connectors ($and, $or). See the Filter API Complete Guide.

Operation Limitation

The filter() operation is only supported in WebAPI mode (Cookie authentication). OpenAPI mode does not support this feature yet.

getOne()

Gets a single record.

async getOne<T = any>(id: string | number): Promise<T>

Parameters:

  • id - Record ID

Return Value:

  • Returns a single record data

Usage Example:

const user = await client.models.users.getOne(123);
console.log("User info:", user);

// Type-safe usage
interface User {
id: number;
name: string;
email: string;
}

const user = await client.models.users.getOne<User>(123);
console.log("Username:", user.name);

create()

Creates a new record.

async create<T = any>(data: Record<string, any>): Promise<T>

Parameters:

  • data - Record data to create

Return Value:

  • Returns the created record data

Usage Example:

const newUser = await client.models.users.create({
name: "John Doe",
email: "john@example.com",
age: 25,
});

console.log("Created user ID:", newUser.id);

update()

Updates an existing record.

async update<T = any>(id: string | number, data: Record<string, any>): Promise<T>

Parameters:

  • id - Record ID
  • data - Data to update

Return Value:

  • Returns the updated record data

Usage Example:

const updatedUser = await client.models.users.update(123, {
name: "Jane Doe",
email: "jane@example.com",
});

console.log("Updated user:", updatedUser);

delete()

Deletes a record.

async delete(id: string | number): Promise<void>

Parameters:

  • id - Record ID to delete

Return Value:

  • No return value

Usage Example:

await client.models.users.delete(123);
console.log("User deleted successfully");
Operation Limitation

The delete() operation is only supported in WebAPI mode (Cookie authentication). OpenAPI mode does not support this operation yet.

getSelectOptions() v1.1.18+

Gets dropdown option data from a data table.

async getSelectOptions(params: SelectOptionsParams): Promise<SelectOption[]>

Parameters:

  • params - Option configuration parameters
    • code - Field name used as option value
    • label - Field name used as display text

Return Value:

  • Returns a standardized options array in the format { label: string, value: string }[]

Usage Example:

// Get user dropdown options
const userOptions = await client.models.users.getSelectOptions({
code: "user_id",
label: "user_name",
});

console.log(userOptions);
// [
// { label: 'Zhang San', value: 'user001' },
// { label: 'Li Si', value: 'user002' }
// ]

// Use in React Select component
import { Select } from "antd";

function UserSelector() {
const [options, setOptions] = useState([]);

useEffect(() => {
const loadOptions = async () => {
const data = await client.models.users.getSelectOptions({
code: "id",
label: "name",
});
setOptions(data);
};
loadOptions();
}, []);

return (
<Select placeholder="Select user">
{options.map((opt) => (
<Option key={opt.value} value={opt.value}>
{opt.label}
</Option>
))}
</Select>
);
}

// Order status selector
const statusOptions = await client.models.orderStatus.getSelectOptions({
code: "status_code",
label: "status_name",
});

// Department selector
const deptOptions = await client.models.departments.getSelectOptions({
code: "dept_id",
label: "dept_name",
});
Operation Limitation

The getSelectOptions() operation is only supported in WebAPI mode (Cookie authentication). OpenAPI mode does not support this feature yet.

getConfig()

Gets model configuration information.

getConfig(): ModelConfig

Return Value:

  • Returns the model configuration object

Usage Example:

const config = client.models.users.getConfig();
console.log("Table name:", config.tableName);
console.log("Dataset ID:", config.datasetCode);

getModelName()

Gets the model name.

getModelName(): string

Return Value:

  • Returns the model name

Usage Example:

const modelName = client.models.users.getModelName();
console.log("Model name:", modelName); // Output: Users

ApiNamespace Class v1.1.19+

Provides API operations such as custom SQL queries, accessible through the client.api namespace.

Methods

executeSql()

Executes custom SQL queries configured on the platform.

async executeSql<T = Record<string, any>>(
sqlCode: string | number,
params?: Record<string, string | number>
): Promise<SqlExecuteResult<T>>

Parameters:

  • sqlCode - SQL code (format: "appCode-sqlId" or numeric ID)
  • params - SQL parameter object (optional), for parameterized queries

Return Value:

  • Returns SQL execution result, including execSuccess and execResult fields

Type Definition:

interface SqlExecuteResult<T> {
execSuccess: boolean; // Whether SQL execution was successful
execResult?: T[]; // Query result array (only exists on success)
}

Usage Example:

// Basic query
const data = await client.api.executeSql("fc8e7777-06e3847d");

if (data.execSuccess && data.execResult) {
console.log("Query results:", data.execResult);
}

// Parameterized query (prevents SQL injection)
const data = await client.api.executeSql("fc8e7777-xxxxx", {
userId: "123",
startDate: "2025-01-01",
});

// With type hints
interface PageStat {
creation_date: string;
page_count: number;
}

const data = await client.api.executeSql<PageStat>("fc8e7777-06e3847d");
if (data.execSuccess && data.execResult) {
data.execResult.forEach((stat) => {
console.log(`Date: ${stat.creation_date}, Count: ${stat.page_count}`);
});
}
Detailed Usage Guide

The SQL API supports complex statistical queries, join queries, custom reports, and other scenarios. See the SQL API Usage Guide.

Configuration Management API

registerModels()

Registers model configuration to the global registry.

function registerModels(config: ModelsConfig, name?: string): void;

Parameters:

  • config - Model configuration object
  • name - Configuration name (default: 'default')

Usage Example:

import { registerModels, CONFIG_NAMES } from "@lovrabet/sdk";

// Register default configuration
registerModels({
appCode: "my-app",
models: {
Users: { tableName: "users", datasetCode: "user-id" },
Posts: { tableName: "posts", datasetCode: "post-id" },
},
});

// Register production environment configuration
registerModels(
{
appCode: "my-app-prod",
models: {
Users: { tableName: "users", datasetCode: "prod-user-id" },
},
},
CONFIG_NAMES.PROD
);

getRegisteredModels()

Gets registered model configuration.

function getRegisteredModels(name: string): ModelsConfig | undefined;

Parameters:

  • name - Configuration name

Return Value:

  • Returns the configuration object or undefined

Usage Example:

const config = getRegisteredModels("default");
if (config) {
console.log("App Code:", config.appCode);
}

getRegisteredConfigNames()

Gets all registered configuration names.

function getRegisteredConfigNames(): string[];

Return Value:

  • Returns an array of configuration names

Usage Example:

const names = getRegisteredConfigNames();
console.log("Registered configurations:", names);
// Output: ['default', 'prod', 'dev']

Constant Definitions

CONFIG_NAMES

Predefined configuration name constants:

export const CONFIG_NAMES = {
DEFAULT: "default",
PROD: "prod",
DEV: "dev",
TEST: "test",
} as const;

ENVIRONMENTS

Environment type constants:

export const ENVIRONMENTS = {
ONLINE: "online",
} as const;

DEFAULTS

Default value constants:

export const DEFAULTS = {
ENV: "online",
TIMEOUT: 30000,
RETRY_COUNT: 3,
PAGE_SIZE: 20,
CURRENT_PAGE: 1,
} as const;

Complete Usage Examples

Basic CRUD Operations

import { registerModels, createClient } from "@lovrabet/sdk";

// 1. Register configuration
registerModels({
appCode: "copybook-app",
models: {
Users: { tableName: "users", datasetCode: "user-dataset-id" },
Characters: { tableName: "characters", datasetCode: "char-dataset-id" },
},
});

// 2. Create client
const client = createClient();

// 3. Complete CRUD operation example
async function crudExample() {
// Create user
const newUser = await client.models.users.create({
name: "Zhang San",
email: "zhangsan@example.com",
grade: 3,
});
console.log("Created user:", newUser);

// Get user list
const userList = await client.models.users.filter({
currentPage: 1,
pageSize: 10,
grade: 3, // Filter third-grade students
});
console.log("User list:", userList.tableData);

// Get single user
const user = await client.models.users.getOne(newUser.id);
console.log("User details:", user);

// Update user
const updatedUser = await client.models.users.update(user.id, {
email: "zhangsan.new@example.com",
});
console.log("Updated user:", updatedUser);

// Delete user
await client.models.users.delete(user.id);
console.log("Delete successful");
}

crudExample();

Multi-Environment Configuration Example

import { registerModels, createClient, CONFIG_NAMES } from "@lovrabet/sdk";

// Development environment configuration
registerModels(
{
appCode: "app-dev-123",
models: {
Users: { tableName: "users", datasetCode: "dev-user-id" },
},
},
CONFIG_NAMES.DEV
);

// Production environment configuration
registerModels(
{
appCode: "app-prod-456",
models: {
Users: { tableName: "users", datasetCode: "prod-user-id" },
},
},
CONFIG_NAMES.PROD
);

// Create different clients based on environment
const isDevelopment = process.env.NODE_ENV === "development";
const client = createClient(
isDevelopment ? CONFIG_NAMES.DEV : CONFIG_NAMES.PROD
);

Authentication Configuration Example

// Token authentication
const client = createClient({
apiConfigName: "default",
token: "your-user-token",
});

// OpenAPI key authentication
const apiClient = createClient({
apiConfigName: "default",
accessKey: "your-access-key",
secretKey: "your-secret-key",
});

// Dynamically set Token
client.setToken("new-token-after-login");

Dynamic Model Access Example

// Get the first available model
const firstModel = client.getModel(0);
const data = await firstModel.filter();

// Iterate through all models
const modelNames = client.getModelList();
for (const name of modelNames) {
const model = client.getModel(name);
const config = model.getConfig();
console.log(`Model ${name}: ${config.tableName}`);
}

Error Handling

The SDK provides a unified error handling mechanism:

try {
const users = await client.models.users.filter();
} catch (error) {
console.error("API call failed:", error);

// Check error type
if (error.status === 401) {
console.log("Authentication failed, need to re-login");
} else if (error.status === 403) {
console.log("Insufficient permissions");
} else if (error.status >= 500) {
console.log("Server error");
}
}

safe Function v1.2.10+

The safe function provides try-catch-free error handling:

import { safe, type SafeResult } from "@lovrabet/sdk";

const { data, error } = await safe(() => client.models.users.filter());

if (error) {
console.error("Failed:", error.message);
return;
}
console.log("Success:", data);

Type Definition:

interface SafeResult<T> {
data: T | null;
error: LovrabetError | null;
}

function safe<T>(
fn: Promise<T> | (() => Promise<T>)
): Promise<SafeResult<T>>;

See the Error Handling Guide for details.

Performance Optimization Tips

1. Model Instance Reuse

// Recommended: reuse client instance
const client = createClient();
export { client };

// Avoid: repeatedly creating clients
function getUsers() {
const client = createClient(); // Creates a new instance every time
return client.models.users.filter();
}

2. Batch Operations

// Recommended: batch create
const users = [
{ name: "User 1", email: "user1@example.com" },
{ name: "User 2", email: "user2@example.com" },
];

const promises = users.map((user) => client.models.users.create(user));
const results = await Promise.all(promises);

3. Reasonable Page Size

// Recommended: set reasonable page size based on actual needs
const users = await client.models.users.filter({
currentPage: 1,
pageSize: 50, // Set based on UI display requirements
});

Core Documentation

API-Specific Documentation

Questions? Check the Troubleshooting documentation or contact technical support.