Skip to content

BFF API reference ​

v1.3.0+

The BFF (Backend For Frontend) API lets you call Backend Functions configured on the Lovrabet platform.

ℹ️ Version requirement This feature is available from SDK v1.3.0.

When to use the BFF API ​

ScenarioRecommended API
Simple CRUD operationsDataset API
Custom SQL queriesSQL API
Complex business logicBFF API ✅
Operations that need server-side processingBFF API ✅

API methods ​

execute() ​

Calls a Backend Function.

Signature ​

TypeScript
client.bff.execute<T>({ scriptName, params, options }: BffExecuteParams): Promise<T>

Parameters ​

ParameterTypeRequiredDescription
scriptNamestring✅Backend Function name
paramsRecord<string, any>❌Function parameters
optionsBffOptions❌Execution options

Return value ​

Returns the business data directly (the SDK unwraps the data field for you).

💡 How it differs from the SQL API

Quick start ​

Basic call ​

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

const client = createClient({
  accessKey: process.env.LOVRABET_ACCESS_KEY,
  appCode: "your-app-code",
});

// 调用后端函数
const result = await client.bff.execute({
  scriptName: 'getUserDashboard'
});

console.log("用户数据:", result);

Call with parameters ​

TypeScript
const price = await client.bff.execute({
  scriptName: 'calculatePrice',
  params: {
    productId: '123',
    quantity: 10,
    userLevel: 'VIP'
  }
});

console.log("计算结果:", price);

TypeScript type support ​

TypeScript
// 定义返回类型
interface PriceResult {
  originalPrice: number;
  discountedPrice: number;
  discount: number;
  finalPrice: number;
}

// 使用泛型
const price = await client.bff.execute<PriceResult>({
  scriptName: 'calculatePrice',
  params: { productId: '123', quantity: 10 }
});

console.log(`原价: ${price.originalPrice}`);
console.log(`折扣: ${price.discount}`);
console.log(`最终价格: ${price.finalPrice}`);

Common use cases ​

Use case 1: price calculation ​

TypeScript
interface CalculatePriceParams {
  productId: string;
  quantity: number;
  couponCode?: string;
}

interface PriceResult {
  unitPrice: number;
  subtotal: number;
  discount: number;
  total: number;
}

async function calculatePrice(params: CalculatePriceParams): Promise<PriceResult> {
  return await client.bff.execute<PriceResult>({
    scriptName: 'calculateOrderPrice',
    params
  });
}

// 使用
const price = await calculatePrice({
  productId: 'prod-001',
  quantity: 5,
  couponCode: 'SUMMER2024'
});

Use case 2: data aggregation ​

TypeScript
interface DashboardStats {
  userCount: number;
  orderCount: number;
  revenue: number;
  topProducts: Array<{ name: string; sales: number }>;
}

async function getDashboardStats(timeRange: string): Promise<DashboardStats> {
  return await client.bff.execute<DashboardStats>({
    scriptName: 'getDashboardStats',
    params: { timeRange }
  });
}

const stats = await getDashboardStats('last7days');
console.log(`总收入: ${stats.revenue}`);

Use case 3: complex business logic ​

TypeScript
// 处理订单逻辑(库存检查、价格计算、优惠券应用等)
interface OrderResult {
  success: boolean;
  orderId?: string;
  message?: string;
}

async function createOrder(items: Array<{productId: string; quantity: number}>) {
  return await client.bff.execute<OrderResult>({
    scriptName: 'processOrder',
    params: { items }
  });
}

const result = await createOrder([
  { productId: 'p1', quantity: 2 },
  { productId: 'p2', quantity: 1 }
]);

if (result.success) {
  console.log(`订单创建成功: ${result.orderId}`);
} else {
  console.error(`订单创建失败: ${result.message}`);
}

Error handling ​

Using the safe function ​

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

const { data: result, error } = await safe(() =>
  client.bff.execute({
    scriptName: 'calculatePrice',
    params: { productId: '123', quantity: 10 }
  })
);

if (error) {
  console.error("调用失败:", error.message, error.description);
  return;
}

console.log("计算结果:", result);

Using try-catch ​

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

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

  console.log("计算结果:", result);
} catch (error) {
  if (error instanceof LovrabetError) {
    if (error.status === 404) {
      console.error("后端函数不存在");
    } else if (error.status === 500) {
      console.error("后端执行错误");
    } else {
      console.error("请求失败:", error.message);
    }
  }
}

FAQ ​

What is the difference between the BFF API and the SQL API? ​

FeatureSQL APIBFF API
PurposeData queriesBusiness logic processing
Return format{ execSuccess, execResult }Business data returned directly
Parameterization#{param} placeholdersJSON parameters
Best forQueries and statisticsComputation and workflows

How do I debug BFF calls? ​

Enable debug mode:

TypeScript
const client = createClient({
  appCode: "your-app",
  accessKey: process.env.ACCESS_KEY,
  options: {
    debug: true,
  },
});

Backend Function not found? ​

Check that:

  1. scriptName exactly matches the function name configured on the platform
  2. The function has been published
  3. The appCode has permission to access the function
  • SQL API guide - custom SQL queries
  • API guide - the Dataset API
  • Advanced features - more advanced capabilities

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