Skip to content

BFF API 参考 ​

v1.3.0+

BFF (Backend For Frontend) API 允许你调用在 Lovrabet 平台上配置的后端函数。

ℹ️ 版本要求此功能从 SDK v1.3.0 版本开始支持。

什么时候使用 BFF API? ​

场景推荐 API
简单的 CRUD 操作Dataset API
自定义 SQL 查询SQL API
复杂业务逻辑计算BFF API ✅
需要后端处理的操作BFF API ✅

API 方法 ​

execute() ​

调用后端函数。

方法签名 ​

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

参数 ​

参数类型必填说明
scriptNamestring✅后端函数名称
paramsRecord<string, any>❌函数参数
optionsBffOptions❌执行选项

返回值 ​

直接返回业务数据(已在 SDK 中从 data 字段提取)。

💡 与 SQL API 的区别

快速开始 ​

基础调用 ​

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);

带参数调用 ​

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

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

TypeScript 类型支持 ​

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}`);

常见使用场景 ​

场景一:价格计算 ​

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'
});

场景二:数据聚合 ​

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}`);

场景三:复杂业务逻辑 ​

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}`);
}

错误处理 ​

使用 safe 函数 ​

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);

使用 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);
    }
  }
}

常见问题 ​

BFF API 和 SQL API 的区别? ​

特性SQL APIBFF API
用途数据查询业务逻辑处理
返回格式{ execSuccess, execResult }直接返回业务数据
参数化支持 #{param}支持 JSON 参数
适用场景查询、统计计算、工作流

如何调试 BFF 调用? ​

启用调试模式:

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

后端函数找不到? ​

检查:

  1. scriptName 是否与平台上配置的函数名完全一致
  2. 函数是否已发布
  3. appCode 是否有访问该函数的权限

相关文档 ​

  • SQL API 使用指南 - 自定义 SQL 查询
  • API 使用指南 - Dataset API
  • 高级功能 - 更多高级特性

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