Skip to content

API Reference


Complete reference for the Lovrabet SDK, with detailed descriptions of every class and method.

🏗️ Core architecture

The Lovrabet SDK is built from a small set of core components:

Plain
LovrabetClient (客户端)
├── models (模型访问器) → ModelManager (模型管理器)
├── AuthManager (认证管理器)
└── HttpClient (HTTP 客户端)
    ├── AuthManager (依赖)
    └── ErrorHandler (错误处理器)

ModelManager (模型管理器)
└── BaseModel[] (模型实例缓存)
    └── HttpClient (依赖)

📋 Core type definitions

ModelConfig

Configuration for a single model:

TypeScript
interface ModelConfig {
  tableName: string; // 数据表名称(必填)
  datasetCode: string; // 数据集代码(必填,唯一标识)
  name?: string; // 显示名称(可选,用于 UI 展示)
  alias?: string; // 别名(可选,用于 client.models.alias 访问)
  dbName?: string; // 数据库名称(可选,用于区分不同数据库)
}

ModelsConfig

Model collection configuration (both array and object formats are supported):

TypeScript
interface ModelsConfig {
  appCode: string; // 应用标识码
  models: ModelConfig[] | Record<string, ModelConfig>; // 模型配置(数组或对象格式)
}

Array format (recommended):

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

Object format (backward compatible):

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

ClientConfig

Full client configuration:

TypeScript
interface ClientConfig {
  // 基础配置
  appCode?: string; // 应用标识码
  runtimeDomain?: string; // 运行态 API 域名(优先使用)
  serverUrl?: string; // 旧字段,已废弃,仍向下兼容
  env?: Environment; // 运行环境,默认 production

  // 认证配置
  authMode?: "openapi" | "client-ak" | "cookie"; // 认证模式
  token?: string; // 用户令牌(Bearer 认证)
  timestamp?: number; // 与 token 配对的时间戳(OpenAPI 模式必需)
  accessKey?: string; // OpenAPI 或 Client AK 访问密钥
  secretKey?: string; // OpenAPI 密钥(client-ak 模式不需要)
  headers?: Record<string, string>; // 额外请求头
  requiresAuth?: boolean; // 是否需要认证,默认 true

  // 模型配置
  models?: ModelConfig[] | Record<string, ModelConfig>; // 模型配置
  apiConfigName?: string; // 引用已注册的配置名称

  // 扩展选项
  options?: {
    timeout?: number; // 请求超时时间(毫秒)
    retryCount?: number; // 重试次数
    debug?: boolean; // 调试模式,打印请求详情 (v1.1.14+)
    onError?: (error: any) => void; // 错误回调
    onRedirectToLogin?: () => void; // 登录重定向回调
  };
}

runtimeDomain takes precedence over serverUrl. New projects should use runtimeDomain; serverUrl is kept only for compatibility with older code. authMode: "client-ak" routes requests through the /client/ endpoints and automatically writes accessKey into the X-User-AK header.

ListParams

List query parameters:

TypeScript
interface ListParams {
  currentPage?: number; // 当前页码 (默认: 1)
  pageSize?: number; // 页面大小 (默认: 20)
  [key: string]: any; // 其他查询参数
}

ListResponse

Paginated response format:

TypeScript
interface ListResponse<T> {
  tableData: T[]; // 数据列表
  paging: {
    totalCount: number; // 总记录数
    currentPage: number; // 当前页码
    pageSize: number; // 页面大小
  };
  tableColumns: any[]; // 列定义
  execResult?: any;
  extend?: Record<string, any>;
}

SortOrder v1.1.16+

Enum for sort direction:

TypeScript
enum SortOrder {
  ASC = "asc",   // 升序
  DESC = "desc", // 降序
}

Usage example:

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

// 使用枚举值(推荐)
const sortList = [{ createTime: SortOrder.DESC }, { name: SortOrder.ASC }];

// 或直接使用字符串
const sortList = [{ createTime: "desc" }, { name: "asc" }];

SortList v1.1.16+

The sort configuration list type:

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

The sort list uses a simple key-value format; each object represents one sort field:

  • key: the field name
  • value: the sort direction ("asc" or "desc")

Usage example:

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

// 单字段排序
const sort1: SortList = [{ id: SortOrder.DESC }];

// 多字段排序
const sort2: SortList = [
  { priority: SortOrder.DESC }, // 第一优先级:按优先级降序
  { createTime: SortOrder.DESC }, // 第二优先级:按创建时间降序
  { name: SortOrder.ASC }, // 第三优先级:按名称升序
];

// 使用排序
const users = await client.models.users.filter(
  { currentPage: 1, pageSize: 20 },
  sort2
);

SelectOption v1.1.18+

Dropdown option data format:

TypeScript
interface SelectOption {
  label: string; // 显示文本
  value: string; // 选项值
}

This is the standard format returned by getSelectOptions(), ready to use directly in frontend components:

TypeScript
const options: SelectOption[] = [
  { label: "张三", value: "user001" },
  { label: "李四", value: "user002" },
];

// 在 React Select 组件中使用
<Select>
  {options.map((opt) => (
    <Option key={opt.value} value={opt.value}>
      {opt.label}
    </Option>
  ))}
</Select>;

SelectOptionsParams v1.1.18+

Dropdown option query parameters:

TypeScript
interface SelectOptionsParams {
  code: string; // 用作选项值的字段名
  label: string; // 用作显示文本的字段名
}

Usage example:

TypeScript
// 从用户表获取下拉选项
const params: SelectOptionsParams = {
  code: "user_id", // 数据表的 user_id 字段作为 value
  label: "user_name", // 数据表的 user_name 字段作为 label
};

const options = await client.models.users.getSelectOptions(params);
// 返回: [{ label: '张三', value: 'user001' }, ...]

// 在订单状态选择中使用
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 and supports several configuration styles.

Function signature

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

Parameters

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

Usage

1. Use a registered configuration name

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

2. Pass model configuration directly

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

3. Use a full client configuration

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

4. Reference a configuration and override selected options

TypeScript
const client = createClient({
  apiConfigName: "default", // 使用预注册的 default 配置
  token: "custom-token", // 但使用自定义 token
});

Return value

Returns a LovrabetClient instance.

📱 LovrabetClient class

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

Client object structure

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

// client 包含以下命名空间:
client.models    // 模型访问器
client.sql       // SQL 客户端 (v1.1.19+)
client.bff       // BFF 客户端 (v1.2.0+)
client.user      // User 客户端
client.services  // 运行态服务:OCR / 文件 (v1.4.3+)
client.api       // API 命名空间(别名,向后兼容)

Properties

models

Model accessor with two access styles:

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

Access styles:

TypeScript
// 标准方式(推荐)- 使用 dataset_ 前缀 + datasetCode
const data1 = await client.models.dataset_xxx.filter();

// 别名方式(语法糖)- 使用配置的 alias
const data2 = await client.models.users.filter();

sql v1.1.19+

SQL client for executing registered custom SQL queries:

TypeScript
public readonly sql: SqlClient

API methods:

MethodDescription
execute({ sqlCode, params })Execute a SQL query (object parameter, recommended)
execute(sqlCode, params)Execute a SQL query (positional arguments, compatible)

Usage example:

TypeScript
// 推荐:对象参数
const result = await client.sql.execute({
  sqlCode: 'fc8e7777-06e3847d',
  params: { userId: '123' }
});

// 兼容:直接传参
const result = await client.sql.execute('fc8e7777-06e3847d', { userId: '123' });

// 别名方式(向后兼容,不推荐)
const result = await client.api.executeSql('fc8e7777-06e3847d', { userId: '123' });

// 检查执行结果
if (result.execSuccess && result.execResult) {
  result.execResult.forEach(row => console.log(row));
}

Return type:

TypeScript
interface SqlExecuteResult<T> {
  execSuccess: boolean;    // SQL 执行是否成功
  execResult?: T[];        // 查询结果数组
}

bff v1.2.0+

BFF client for calling Backend For Frontend endpoints:

TypeScript
public readonly bff: BffClient

API methods:

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

Usage example:

TypeScript
// 无参数调用
const result = await client.bff.execute({
  scriptName: 'getUserDashboard'
});

// 带参数调用
const result = await client.bff.execute({
  scriptName: 'calculatePrice',
  params: { productId: '123', quantity: 10 }
});

// 带类型提示
interface DashboardData {
  userCount: number;
  orderCount: number;
}
const dashboard = await client.bff.execute<DashboardData>({
  scriptName: 'getUserDashboard'
});

// 别名方式(向后兼容,不推荐)
const result = await client.api.bff('calculatePrice', {
  productId: '123',
  quantity: 10
});

Return value: the business data itself (the SDK already unwraps the data field)

Error handling: HTTP errors throw a LovrabetError

user

User client for retrieving user information:

TypeScript
public readonly user: UserClient

API methods:

MethodDescription
getList()Get the user list

Usage example:

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

services v1.4.3+

Runtime services namespace, providing general platform capabilities that are not tied to a dataset or BFF (OCR, files).

TypeScript
public readonly services: ServicesNamespace

Routing is automatic based on authMode: available for cookie / client-ak; with openapi it throws *_AUTH_MODE_UNSUPPORTED before sending. See Runtime Services.

OCR recognition:

TypeScript
client.services.ocr.recognize(request: OcrRecognizeRequest): Promise<OcrRecognizeResponse>
TypeScript
import { createClient, OcrType } from "@lovrabet/sdk";

const client = createClient({ appCode: "app", authMode: "client-ak", accessKey: AK });
const result = await client.services.ocr.recognize({
  url: "https://example.com/invoice.png",
  type: OcrType.Invoice,
});

File upload / access URL:

TypeScript
client.services.file.upload(request: FileUploadRequest): Promise<FileUploadResponse>
client.services.file.queryUrl(request: FileQueryUrlRequest): Promise<FileUrlResponse>
TypeScript
const uploaded = await client.services.file.upload({ file: input.files[0] });
const access = await client.services.file.queryUrl({ filePath: uploaded.filePath! });

Related exports: ServicesNamespace, OcrClient, FileClient, OcrType, OCR_TYPES.

api

API namespace providing backward-compatible aliases:

TypeScript
public readonly api: ApiNamespace

Recommended style vs alias:

RecommendedAlias (compatibility)
client.sql.execute()client.api.executeSql()
client.bff.execute()client.api.bff()
client.user.getList()client.api.getUserList()

💡 Tip Prefer the client.sql, client.bff, and client.user namespaces — the code reads cleaner and type hints are better.

Methods

setToken()

Sets the user authentication token.

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

Parameters:

  • token - the user authentication token
  • timestamp - the timestamp paired with the token (optional, required in OpenAPI mode)

Usage example:

TypeScript
// WebAPI 模式(Cookie 认证)
client.setToken("your-new-token");

// OpenAPI 模式(需要 timestamp)
client.setToken("your-new-token", Date.now());

getConfig()

Gets the client configuration.

TypeScript
getConfig(): ClientConfig

Return value:

  • Returns the current client configuration object

Usage example:

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

getBaseUrl()

Gets the API base URL.

TypeScript
getBaseUrl(): string

Return value:

  • Returns the full API base URL

Usage example:

TypeScript
const baseUrl = client.getBaseUrl();
// 输出: https://api.lovrabet.com/api

getModelList()

Gets the names of all available models.

TypeScript
getModelList(): string[]

Return value:

  • Returns an array of model names

Usage example:

TypeScript
const modelNames = client.getModelList();
console.log("可用模型:", modelNames);
// 输出: ['Users', 'Posts', 'Comments']

getModel()

Gets a model instance by index or name.

TypeScript
getModel(indexOrName: number | string): BaseModelMethods

Parameters:

  • indexOrName - the model index (0-based) or the model name

Return value:

  • Returns a BaseModel instance

Usage example:

TypeScript
// 通过索引获取第一个模型
const firstModel = client.getModel(0);
const data = await firstModel.filter();

// 通过名称获取模型
const userModel = client.getModel("Users");
const user = await userModel.getOne(123);

📊 BaseModel class

The base class for all data models, providing the full CRUD interface.

Methods

getList()

Gets a list of records with pagination and multi-field sorting.

TypeScript
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 the paginated data response

Usage example:

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

// 基础查询
const response = await client.models.users.filter();

// 分页查询
const response = await client.models.users.filter({
  currentPage: 2,
  pageSize: 50,
});

// 带条件查询
const response = await client.models.users.filter({
  currentPage: 1,
  pageSize: 20,
  name: "John", // 自定义查询条件
  status: "active",
});

// 带排序查询(单字段)
const response = await client.models.users.filter(
  { currentPage: 1, pageSize: 20 },
  [{ createTime: SortOrder.DESC }] // 按创建时间降序
);

// 带排序查询(多字段)
const response = await client.models.products.filter(
  { currentPage: 1, pageSize: 20 },
  [
    { priority: SortOrder.DESC }, // 优先按优先级降序
    { createTime: SortOrder.DESC }, // 再按创建时间降序
    { name: SortOrder.ASC }, // 最后按名称升序
  ]
);

console.log("用户列表:", response.tableData);
console.log("总数:", response.paging.totalCount);
console.log("当前页:", response.paging.currentPage);

filter() v1.1.21+

Advanced filtered query supporting complex conditions, field selection, sorting, and pagination (recommended).

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

Parameters:

  • params - Filter query parameters (optional)

    • where - query conditions; supports operators such as $eq, $ne, $gte, $lte, $in, $contain, and $notNull
    • select - the list of fields to return
    • orderBy - sort rules
    • currentPage - current page number
    • pageSize - page size

Return value:

  • Returns the paginated data response

Quick example:

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

// 复杂条件查询
const response = await client.models.users.filter({
  where: {
    $and: [
      { age: { $gte: 18, $lte: 45 } },           // 年龄范围
      { country: { $in: ['中国', '美国'] } },     // 国家列表
      { name: { $contain: 'hello' } }             // 名称包含
    ]
  },
  select: ['id', 'name', 'age', 'country'],      // 只返回这些字段
  orderBy: [{ createTime: SortOrder.DESC }],     // 按创建时间降序
  currentPage: 1,
  pageSize: 20
});

💡 In-depth guide The filter API is a powerful query interface supporting all condition operators ($eq, $ne, $gte, $lte, $in, $contain, $startWith, $endWith, $notNull) and logical connectors ($and, $or). See the complete Filter API guide.

getOne()

Gets a single record.

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

Parameters:

  • id - the record ID

Return value:

  • Returns the record data

Usage example:

TypeScript
const user = await client.models.users.getOne(123);
console.log("用户信息:", user);

// 类型安全的用法
interface User {
  id: number;
  name: string;
  email: string;
}

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

create()

Creates a new record.

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

Parameters:

  • data - the record data to create

Return value:

  • Returns the created record data

Usage example:

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

console.log("新建用户 ID:", newUser.id);

batchCreate() v1.4.1+

Creates records in batch, up to 1,000 per call.

TypeScript
async batchCreate<T = any>(items: Record<string, any>[]): Promise<T>

Parameters:

  • items - the array of records to create; it must be a non-empty array of at most 1,000 items

Request body differences:

  • OpenAPI mode: uses paramList
  • WebAPI / Client AK mode: sends the raw array as the request body

Usage example:

TypeScript
const result = await client.models.users.batchCreate([
  { name: "John Doe", email: "john@example.com" },
  { name: "Jane Doe", email: "jane@example.com" },
]);

update()

Updates an existing record.

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

Parameters:

  • id - the record ID
  • data - the data to update

Return value:

  • Returns the updated record data

Usage example:

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

console.log("更新后的用户:", updatedUser);

delete()

Deletes a record.

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

Parameters:

  • id - the ID of the record to delete

Return value:

  • No return value

Usage example:

TypeScript
await client.models.users.delete(123);
console.log("用户删除成功");

⚠️ Operation restriction The delete() operation is supported only in WebAPI mode (Cookie authentication). It is not yet available in OpenAPI mode.

getSelectOptions() v1.1.18+

Gets dropdown option data for the table.

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

Parameters:

  • params - option configuration parameters

    • code - the field name to use as the option value
    • label - the field name to use as the display text

Return value:

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

Usage example:

TypeScript
// 获取用户下拉选项
const userOptions = await client.models.users.getSelectOptions({
  code: "user_id",
  label: "user_name",
});

console.log(userOptions);
// [
//   { label: '张三', value: 'user001' },
//   { label: '李四', value: 'user002' }
// ]

// 在 React Select 组件中使用
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="选择用户">
      {options.map((opt) => (
        <Option key={opt.value} value={opt.value}>
          {opt.label}
        </Option>
      ))}
    </Select>
  );
}

// 订单状态选择器
const statusOptions = await client.models.orderStatus.getSelectOptions({
  code: "status_code",
  label: "status_name",
});

// 部门选择器
const deptOptions = await client.models.departments.getSelectOptions({
  code: "dept_id",
  label: "dept_name",
});

⚠️ Operation restriction The getSelectOptions() operation is supported only in WebAPI mode (Cookie authentication). It is not yet available in OpenAPI mode.

getConfig()

Gets the model configuration.

TypeScript
getConfig(): ModelConfig

Return value:

  • Returns the model configuration object

Usage example:

TypeScript
const config = client.models.users.getConfig();
console.log("表名:", config.tableName);
console.log("数据集 ID:", config.datasetCode);

getModelName()

Gets the model name.

TypeScript
getModelName(): string

Return value:

  • Returns the model name

Usage example:

TypeScript
const modelName = client.models.users.getModelName();
console.log("模型名称:", modelName); // 输出: Users

🔌 ApiNamespace class v1.1.19+

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

Methods

executeSql()

Executes a custom SQL query configured on the platform.

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

Parameters:

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

Return value:

  • Returns the SQL execution result, containing execSuccess and execResult fields

Type definition:

TypeScript
interface SqlExecuteResult<T> {
  execSuccess: boolean; // SQL 执行是否成功
  execResult?: T[]; // 查询结果数组(仅成功时存在)
}

Usage example:

TypeScript
// 基础查询
const data = await client.api.executeSql("fc8e7777-06e3847d");

if (data.execSuccess && data.execResult) {
  console.log("查询结果:", data.execResult);
}

// 参数化查询(防止 SQL 注入)
const data = await client.api.executeSql("fc8e7777-xxxxx", {
  userId: "123",
  startDate: "2025-01-01",
});

// 带类型提示
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(`日期: ${stat.creation_date}, 数量: ${stat.page_count}`);
  });
}

💡 In-depth guide The SQL API covers complex statistical queries, joins, custom reports, and more. See the SQL API guide.

🗂️ Configuration management API

registerModels()

Registers model configuration in the global registry.

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

Parameters:

  • config - the model configuration object
  • name - the configuration name (default: 'default')

Usage example:

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

// 注册默认配置
registerModels({
  appCode: "my-app",
  models: {
    Users: { tableName: "users", datasetCode: "user-id" },
    Posts: { tableName: "posts", datasetCode: "post-id" },
  },
});

// 注册生产环境配置
registerModels(
  {
    appCode: "my-app-prod",
    models: {
      Users: { tableName: "users", datasetCode: "prod-user-id" },
    },
  },
  CONFIG_NAMES.PROD
);

getRegisteredModels()

Gets a registered model configuration.

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

Parameters:

  • name - the configuration name

Return value:

  • Returns the configuration object or undefined

Usage example:

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

getRegisteredConfigNames()

Gets the names of all registered configurations.

TypeScript
function getRegisteredConfigNames(): string[];

Return value:

  • Returns an array of configuration names

Usage example:

TypeScript
const names = getRegisteredConfigNames();
console.log("已注册配置:", names);
// 输出: ['default', 'prod', 'dev']

🔗 Constants

CONFIG_NAMES

Predefined configuration name constants:

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

ENVIRONMENTS

Environment type constants:

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

DEFAULTS

Default value constants:

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

📋 Complete usage examples

Basic CRUD

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

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

// 2. 创建客户端
const client = createClient();

// 3. 完整的 CRUD 操作示例
async function crudExample() {
  // 创建用户
  const newUser = await client.models.users.create({
    name: "张三",
    email: "zhangsan@example.com",
    grade: 3,
  });
  console.log("创建用户:", newUser);

  // 获取用户列表
  const userList = await client.models.users.filter({
    currentPage: 1,
    pageSize: 10,
    grade: 3, // 筛选三年级学生
  });
  console.log("用户列表:", userList.tableData);

  // 获取单个用户
  const user = await client.models.users.getOne(newUser.id);
  console.log("用户详情:", user);

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

  // 删除用户
  await client.models.users.delete(user.id);
  console.log("删除成功");
}

crudExample();

Multi-environment configuration

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

// 开发环境配置
registerModels(
  {
    appCode: "app-dev-123",
    models: {
      Users: { tableName: "users", datasetCode: "dev-user-id" },
    },
  },
  CONFIG_NAMES.DEV
);

// 生产环境配置
registerModels(
  {
    appCode: "app-prod-456",
    models: {
      Users: { tableName: "users", datasetCode: "prod-user-id" },
    },
  },
  CONFIG_NAMES.PROD
);

// 根据环境创建不同客户端
const isDevelopment = process.env.NODE_ENV === "development";
const client = createClient(
  isDevelopment ? CONFIG_NAMES.DEV : CONFIG_NAMES.PROD
);

Authentication configuration

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

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

// 动态设置 Token
client.setToken("new-token-after-login");

Dynamic model access

TypeScript
// 获取第一个可用模型
const firstModel = client.getModel(0);
const data = await firstModel.filter();

// 遍历所有模型
const modelNames = client.getModelList();
for (const name of modelNames) {
  const model = client.getModel(name);
  const config = model.getConfig();
  console.log(`模型 ${name}: ${config.tableName}`);
}

🚨 Error handling

The SDK provides a unified error-handling mechanism:

TypeScript
try {
  const users = await client.models.users.filter();
} catch (error) {
  console.error("API 调用失败:", error);

  // 检查错误类型
  if (error.status === 401) {
    console.log("认证失败,需要重新登录");
  } else if (error.status === 403) {
    console.log("权限不足");
  } else if (error.status >= 500) {
    console.log("服务器错误");
  }
}

The safe function v1.2.10+

The safe function offers error handling without try-catch:

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

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

if (error) {
  console.error("失败:", error.message);
  return;
}
console.log("成功:", data);

Type definition:

TypeScript
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.

⚡ Performance tips

1. Reuse client instances

TypeScript
// ✅ 推荐:复用客户端实例
const client = createClient();
export { client };

// ❌ 避免:重复创建客户端
function getUsers() {
  const client = createClient(); // 每次都创建新实例
  return client.models.users.filter();
}

2. Batch operations

TypeScript
// ✅ 推荐:批量创建
const users = [
  { name: "用户1", email: "user1@example.com" },
  { name: "用户2", email: "user2@example.com" },
];

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

3. Choose a sensible page size

TypeScript
// ✅ 推荐:根据实际需求设置合理的页面大小
const users = await client.models.users.filter({
  currentPage: 1,
  pageSize: 50, // 根据 UI 显示需求设置
});

Core docs

  • Quick Start — get running in 5 minutes
  • Configuration — detailed configuration reference
  • Authentication — auth mode setup
  • Real-world examples — complete integration examples
  • Troubleshooting — fixes for common issues

API-specific docs

  • Filter API guide — advanced queries in depth
  • SQL API guide — custom SQL queries
  • Error handling guide — best practices

Questions? See the troubleshooting guide or contact technical support.

基于飞书知识库同步生成,内容以飞书源文档为准