BFF API Reference
BFF (Backend For Frontend) API allows you to call backend functions configured on the Lovrabet platform.
Version Requirement
This feature is supported from SDK v1.3.0 onwards.
When to Use BFF API?
| Scenario | Recommended API |
|---|---|
| Simple CRUD operations | Dataset API |
| Custom SQL queries | SQL API |
| Complex business logic calculations | BFF API ✅ |
| Operations requiring backend processing | BFF API ✅ |
API Methods
execute()
Call a backend function.
Method Signature
client.bff.execute<T>({ scriptName, params, options }: BffExecuteParams): Promise<T>
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
scriptName | string | ✅ | Backend function name |
params | Record<string, any> | ❌ | Function parameters |
options | BffOptions | ❌ | Execution options |
Return Value
Directly returns business data (already extracted from data field in SDK).
Difference from SQL API
- SQL API returns
{ execSuccess, execResult }, requires checking business status - BFF API directly returns business data, HTTP errors throw
LovrabetError
Quick Start
Basic Call
import { createClient } from "@lovrabet/sdk";
const client = createClient({
accessKey: process.env.LOVRABET_ACCESS_KEY,
appCode: "your-app-code",
});
// Call backend function
const result = await client.bff.execute({
scriptName: 'getUserDashboard'
});
console.log("User data:", result);
Call with Parameters
const price = await client.bff.execute({
scriptName: 'calculatePrice',
params: {
productId: '123',
quantity: 10,
userLevel: 'VIP'
}
});
console.log("Calculation result:", price);
TypeScript Type Support
// Define return type
interface PriceResult {
originalPrice: number;
discountedPrice: number;
discount: number;
finalPrice: number;
}
// Use generics
const price = await client.bff.execute<PriceResult>({
scriptName: 'calculatePrice',
params: { productId: '123', quantity: 10 }
});
console.log(`Original price: ${price.originalPrice}`);
console.log(`Discount: ${price.discount}`);
console.log(`Final price: ${price.finalPrice}`);
Common Use Cases
Scenario 1: Price Calculation
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
});
}
// Usage
const price = await calculatePrice({
productId: 'prod-001',
quantity: 5,
couponCode: 'SUMMER2024'
});
Scenario 2: Data Aggregation
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(`Total revenue: ${stats.revenue}`);
Scenario 3: Complex Business Logic
// Process order logic (inventory check, price calculation, coupon application, etc.)
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(`Order created successfully: ${result.orderId}`);
} else {
console.error(`Order creation failed: ${result.message}`);
}
Error Handling
Using safe Function
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("Call failed:", error.message, error.description);
return;
}
console.log("Calculation result:", result);
Using try-catch
import { LovrabetError } from "@lovrabet/sdk";
try {
const result = await client.bff.execute({
scriptName: 'calculatePrice',
params: { productId: '123', quantity: 10 }
});
console.log("Calculation result:", result);
} catch (error) {
if (error instanceof LovrabetError) {
if (error.status === 404) {
console.error("Backend function does not exist");
} else if (error.status === 500) {
console.error("Backend execution error");
} else {
console.error("Request failed:", error.message);
}
}
}
FAQ
What's the difference between BFF API and SQL API?
| Feature | SQL API | BFF API |
|---|---|---|
| Purpose | Data queries | Business logic processing |
| Return format | { execSuccess, execResult } | Directly returns business data |
| Parameterization | Supports #{param} | Supports JSON parameters |
| Use cases | Queries, statistics | Calculations, workflows |
How to debug BFF calls?
Enable debug mode:
const client = createClient({
appCode: "your-app",
accessKey: process.env.ACCESS_KEY,
options: {
debug: true,
},
});
Backend function not found?
Check:
- Is
scriptNameexactly the same as the function name configured on the platform - Is the function published
- Does appCode have permission to access this function
Related Documentation
- SQL API Guide - Custom SQL queries
- API Usage Guide - Dataset API
- Advanced Features - More advanced features