API Reference
Complete Lovrabet SDK API reference documentation, including detailed descriptions of all classes and methods.
🏗️ Core Architecture
Lovrabet SDK adopts a modular architecture design, mainly 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; // Database 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; // Application identifier 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; // Application identifier code
serverUrl?: string; // Server address
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 access key (signature authentication)
secretKey?: string; // OpenAPI secret key (signature authentication)
requiresAuth?: boolean; // Whether authentication is required, defaults to true
// Model configuration
models?: ModelConfig[] | Record<string, ModelConfig>; // Model configuration
apiConfigName?: string; // Reference to registered configuration name
// Extension options
options?: {
timeout?: number; // Request timeout (milliseconds)
retryCount?: number; // Retry count
debug?: boolean; // Debug mode, prints 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 value (recommended)
const sortList = [{ createTime: SortOrder.DESC }, { name: SortOrder.ASC }];
// Or use string directly
const sortList = [{ createTime: "desc" }, { name: "asc" }];
SortList v1.1.16+
Sort configuration list type:
type SortList = Record<string, "asc" | "desc">[];
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 sort
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" },
];
// Using 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 to use as option value
label: string; // Field name to use as display text
}
Usage example:
// Get dropdown options from user table
const params: SelectOptionsParams = {
code: "user_id", // user_id field from database table as value
label: "user_name", // user_name field from database table as label
};
const options = await client.models.users.getSelectOptions(params);
// Returns: [{ label: 'Zhang San', value: 'user001' }, ...]
// Using in order status selection
const statusParams: SelectOptionsParams = {
code: "status_code",
label: "status_name",
};
const statusOptions = await client.models.orderStatus.getSelectOptions(
statusParams
);
🏭 Factory Functions
createClient()
Create SDK client instance, supports multiple configuration methods.
Function Signature
function createClient(
config?: Partial<ClientConfig> | ModelsConfig | string
): LovrabetClient;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
config | Partial<ClientConfig> | ModelsConfig | string | 'default' | Client configuration |
Usage
1. Using pre-registered configuration name
const client = createClient("default");
const prodClient = createClient("prod");
2. Directly passing model configuration
const client = createClient({
appCode: "my-app",
models: {
Users: { tableName: "users", datasetCode: "user-id" },
Posts: { tableName: "posts", datasetCode: "post-id" },
},
});
3. Using complete client configuration
const client = createClient({
appCode: "my-app",
token: "your-token",
models: {
users: { tableName: "users", datasetCode: "8d2dcbae08b54bdd84c00be558ed48df" },
},
options: {
timeout: 30000,
retryCount: 3,
},
});
4. Referencing configuration but overriding some options
const client = createClient({
apiConfigName: "default", // Use pre-registered default configuration
token: "custom-token", // But use custom token
});
Return Value
Returns LovrabetClient instance.
📱 LovrabetClient Class
The main client class of the SDK, providing model access and configuration management features.
Properties
models
Model accessor, supports dynamic model access:
public models: any;
Usage example:
// Access directly through model name
const users = await client.models.users.filter();
const posts = await client.models.posts.getOne(123);
Methods
setToken()
Set user authentication token.
setToken(token: string, timestamp?: number): void
Parameters:
token- User authentication tokentimestamp- Timestamp paired with 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()
Get client configuration information.
getConfig(): ClientConfig
Return value:
- Returns current client configuration object
Usage example:
const config = client.getConfig();
console.log("App Code:", config.appCode);
getBaseUrl()
Get API base URL.
getBaseUrl(): string
Return value:
- Returns complete API base URL
Usage example:
const baseUrl = client.getBaseUrl();
// Output: https://api.lovrabet.com/api
getModelList()
Get list of all available model names.
getModelList(): string[]
Return value:
- Returns array of model names
Usage example:
const modelNames = client.getModelList();
console.log("Available models:", modelNames);
// Output: ['Users', 'Posts', 'Comments']
getModel()
Get model instance by index or name.
getModel(indexOrName: number | string): BaseModelMethods
Parameters:
indexOrName- Model index (starting from 0) or model name
Return value:
- Returns BaseModel instance
Usage example:
// Get 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
Base class for all data models, providing complete CRUD operation interface.
Methods
getList()
Get data list, supports pagination query 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,
});
// Query with conditions
const response = await client.models.users.filter({
currentPage: 1,
pageSize: 20,
name: "John", // Custom query condition
status: "active",
});
// Query with sorting (single field)
const response = await client.models.users.filter(
{ currentPage: 1, pageSize: 20 },
[{ createTime: SortOrder.DESC }] // Sort by creation time descending
);
// Query with sorting (multiple fields)
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 filtering query method, supports complex conditions, field selection, sorting and pagination (recommended).
async filter<T = any>(params?: FilterParams): Promise<ListResponse<T>>
Parameters:
params- Filter query parameters (optional)where- Query conditions, supports operators like$eq,$ne,$gte,$lte,$in,$contain, etc.select- List of fields to returnorderBy- Sort rulescurrentPage- Current page numberpageSize- Items per page
Return value:
- Returns paginated data response
Quick example:
import { SortOrder } from "@lovrabet/sdk";
// Complex condition 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
});
The filter API provides powerful query capabilities, supporting all conditional operators ($eq, $ne, $gte, $lte, $in, $contain, $startWith, $endWith) and logical connectors ($and, $or). See Filter API Complete Guide for details.
The filter() operation is only supported in WebAPI mode (Cookie authentication). OpenAPI mode does not currently support this feature.
getOne()
Get a single record.
async getOne<T = any>(id: string | number): Promise<T>
Parameters:
id- Record ID
Return value:
- Returns 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("User name:", user.name);
create()
Create a new record.
async create<T = any>(data: Record<string, any>): Promise<T>
Parameters:
data- Record data to create
Return value:
- Returns created record data
Usage example:
const newUser = await client.models.users.create({
name: "John Doe",
email: "john@example.com",
age: 25,
});
console.log("New user ID:", newUser.id);
update()
Update an existing record.
async update<T = any>(id: string | number, data: Record<string, any>): Promise<T>
Parameters:
id- Record IDdata- Data to update
Return value:
- Returns 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()
Delete a record.
async delete(id: string | number): Promise<void>
Parameters:
id- ID of record to delete
Return value:
- No return value
Usage example:
await client.models.users.delete(123);
console.log("User deleted successfully");
The delete() operation is only supported in WebAPI mode (Cookie authentication). OpenAPI mode does not currently support this operation.
getSelectOptions() v1.1.18+
Get dropdown option data from the data table.
async getSelectOptions(params: SelectOptionsParams): Promise<SelectOption[]>
Parameters:
params- Option configuration parameterscode- Field name to use as option valuelabel- Field name to use as display text
Return value:
- Returns standardized option array in 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' }
// ]
// Using 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",
});
The getSelectOptions() operation is only supported in WebAPI mode (Cookie authentication). OpenAPI mode does not currently support this feature.
getConfig()
Get model configuration information.
getConfig(): ModelConfig
Return value:
- Returns model configuration object
Usage example:
const config = client.models.users.getConfig();
console.log("Table name:", config.tableName);
console.log("Dataset ID:", config.datasetCode);
getModelName()
Get model name.
getModelName(): string
Return value:
- Returns model name
Usage example:
const modelName = client.models.users.getModelName();
console.log("Model name:", modelName); // Output: Users
🔌 ApiNamespace Class v1.1.19+
Provides custom SQL query and other API operations, accessible through the client.api namespace.
Methods
executeSql()
Execute custom SQL query 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, containing
execSuccessandexecResultfields
Type definition:
interface SqlExecuteResult<T> {
execSuccess: boolean; // Whether SQL execution succeeded
execResult?: T[]; // Query result array (only present on success)
}
Usage example:
// Basic query
const data = await client.api.executeSql("fc8e7777-06e3847d");
if (data.execSuccess && data.execResult) {
console.log("Query result:", data.execResult);
}
// Parameterized query (prevent 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}`);
});
}
SQL API supports complex statistical queries, join queries, custom reports and other scenarios. See SQL API Usage Guide for details.
🗂️ Configuration Management API
registerModels()
Register model configuration to global registry.
function registerModels(config: ModelsConfig, name?: string): void;
Parameters:
config- Model configuration objectname- 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()
Get registered model configuration.
function getRegisteredModels(name: string): ModelsConfig | undefined;
Parameters:
name- Configuration name
Return value:
- Returns configuration object or undefined
Usage example:
const config = getRegisteredModels("default");
if (config) {
console.log("App Code:", config.appCode);
}
getRegisteredConfigNames()
Get all registered configuration names.
function getRegisteredConfigNames(): string[];
Return value:
- Returns configuration name array
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 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
SDK provides 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");
}
}
⚡ Performance Optimization Suggestions
1. Model Instance Reuse
// ✅ Recommended: Reuse client instance
const client = createClient();
export { client };
// ❌ Avoid: Repeatedly creating clients
function getUsers() {
const client = createClient(); // Creating 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 needs
});
📚 Related Documentation
- Quick Start - Get started in 5 minutes
- Configuration Details - Detailed configuration instructions
- Authentication Configuration - Authentication method configuration
- Practical Application Examples - Complete integration examples
- Troubleshooting - Common problem resolution
Have questions? Check the Troubleshooting Documentation or contact technical support.