Skip to content

Platform Services (OCR / Files)


client.services is the platform services namespace introduced in @lovrabet/sdk v1.4.3+. It exposes general-purpose platform capabilities that are not tied to any dataset or BFF. It currently includes two services: OCR recognition and file upload / access URL.

Requirements: SDK v1.4.3+ | Imports: createClient, OcrType, OCR_TYPES

typescript
client.services.ocr    // OCR 识别
client.services.file   // 文件上传与访问 URL 查询

🧭 Auth Modes and Routing

Both the OCR and file services select the server-side route automatically based on authMode:

authModeOCR routeFile routeDescription
cookieGET /api/ocr/recognize-text/api/common/uploadFile, /api/common/queryFileUrlWebAPI, carries the user's Cookie
client-akPOST /client/ocr/client/uploadFile, /client/queryFileUrlClient API, carries X-User-AK
openapi❌ throws OCR_AUTH_MODE_UNSUPPORTED❌ throws FILE_AUTH_MODE_UNSUPPORTEDNo corresponding contract yet

💡 Both supported modes use runtimeDomain — the auth mode only determines the route prefix and request headers. OpenAPI (dataset signature) mode does not support these two services.


🔍 OCR: client.services.ocr.recognize()

API Signature

typescript
client.services.ocr.recognize(request: OcrRecognizeRequest): Promise<OcrRecognizeResponse>
typescript
interface OcrRecognizeRequest {
  url: string;            // 公网可访问的图片 / 文件 URL(必填)
  type: OcrType;          // OCR 识别类型(必填)
  options?: ServiceRequestOptions; // 可选 fetch 设置(method/body 由 SDK 控制)
}

Supported Recognition Types

Reference the OcrType enum instead of hand-writing strings; OCR_TYPES is a read-only array you can drop straight into a dropdown or use for capability discovery.

OcrTypeDescription
GeneralGeneral-purpose text recognition
InvoiceVAT invoice
AdvancedHigh-precision full-text recognition
AdvancedCoordinateHigh precision (with coordinates)
AdvancedGeneralHigh-precision general
IdCardID card
BankCardBank card
BusinessLicenseBusiness license
DrivingLicenseDriver's license
CarNumberLicense plate
TableTable
typescript
import { createClient, OcrType, OCR_TYPES } from "@lovrabet/sdk";

const client = createClient({
  appCode: "your-app-code",
  authMode: "cookie",
  // 浏览器会自动携带 Cookie;Node.js 可在此传入 cookie 字段
});

const result = await client.services.ocr.recognize({
  url: "https://example.com/invoice.png",
  type: OcrType.Invoice,
});

console.log(result.text);     // 全文文本
console.log(result.kvData);   // 结构化键值(发票号、金额等)
console.log(OCR_TYPES);       // ['General', 'Invoice', ...] 用于下拉框

Example: Client AK scenario (server-side)

typescript
import { createClient, OcrType } from "@lovrabet/sdk";

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

const result = await client.services.ocr.recognize({
  url: "https://example.com/license.png",
  type: OcrType.BusinessLicense,
});

Response

typescript
interface OcrRecognizeResponse {
  requestId?: string;
  type?: OcrType;
  text?: string;                 // 全文文本
  lines?: string[];              // 按行拆分
  kvData?: Record<string, string>; // 结构化键值
  width?: number;
  height?: number;
  pageNo?: number | null;
  // ...其余字段随识别类型变化,均为可选
}

⚠️ The OCR API currently accepts URLs only — it does not upload local files. To recognize a local file, first upload it with client.services.file.upload() to get an accessible URL, then pass that URL to recognize().


📎 File Service: client.services.file

Upload: upload()

typescript
client.services.file.upload(request: FileUploadRequest): Promise<FileUploadResponse>
typescript
interface FileUploadRequest {
  file: Blob;             // 浏览器 File 或标准 Blob(必填)
  fileName?: string;      // 可选文件名;Blob 无 name 时必填,否则回退为 upload.bin
  options?: ServiceRequestOptions;
}

Upload from the browser (input.files[0] is a standard File):

typescript
const client = createClient({ appCode: "your-app-code", authMode: "cookie" });

const uploaded = await client.services.file.upload({ file: input.files[0] });
console.log(uploaded.filePath); // 持久引用,建议保存到业务字段

Upload from Node.js (pass a standard Blob with an explicit file name):

typescript
const uploaded = await client.services.file.upload({
  file: new Blob([buffer], { type: "application/pdf" }),
  fileName: "invoice.pdf",
});

Response:

typescript
interface FileUploadResponse {
  fileName?: string | null;
  filePath?: string | null;   // ⭐ 持久引用,适合长期保存
  fileUrl?: string | null;    // 临时访问 URL
  downloadFlag?: boolean;
  fileType?: string | null;
  size?: number | null;
  sourceDir?: string | null;
}

Query an access URL: queryUrl()

typescript
client.services.file.queryUrl(request: FileQueryUrlRequest): Promise<FileUrlResponse>
typescript
interface FileQueryUrlRequest {
  filePath: string;        // upload() 返回的 filePath(必填)
  download?: boolean;      // true 返回下载 URL,默认 false(预览 URL)
  longTerm?: boolean;      // 是否申请长期 URL,默认 false
  options?: ServiceRequestOptions;
}
typescript
const access = await client.services.file.queryUrl({
  filePath: uploaded.filePath!,
});
console.log(access.fileUrl);

// 需要下载链接
const dl = await client.services.file.queryUrl({
  filePath: uploaded.filePath!,
  download: true,
});

filePath vs fileUrl: which to use when

FieldUse forLifetime
filePathA stable reference to store in business fields; swap it for a URL whenever neededLong-term
fileUrlTemporary previews, OCR input, short-lived consumptionShort-term
longTerm: trueRequest only when the content must be displayed long-term via URL aloneLong-term

💡 Recommended: store only filePath in your business tables; call queryUrl() to exchange it for a temporary URL when you need to display or download.


🛡️ Error Handling

The services throw LovrabetError on validation failures or unsupported auth modes. The error code and description are all you need to pinpoint the cause:

codeTriggered whenKey description fields
OCR_URL_REQUIREDurl is emptyfield: "url"
OCR_TYPE_UNSUPPORTEDtype is not in OCR_TYPESsupportedTypes
OCR_AUTH_MODE_UNSUPPORTEDOCR is called in OpenAPI modesupportedAuthModes: ["cookie","client-ak"]
FILE_REQUIREDfile is not a Blob/Filefield: "file"
FILE_PATH_REQUIREDfilePath passed to queryUrl is emptyfield: "filePath"
FILE_AUTH_MODE_UNSUPPORTEDFile service is called in OpenAPI modesupportedAuthModes: ["cookie","client-ak"]
typescript
import { LovrabetError } from "@lovrabet/sdk";

try {
  await client.services.ocr.recognize({ url: "", type: OcrType.Invoice });
} catch (e) {
  if (e instanceof LovrabetError) {
    console.log(e.code);        // 'OCR_URL_REQUIRED'
    console.log(e.description); // { field: 'url', suggestion: '...' }
  }
}

📖 Next Steps

  • Authentication - configuring all four modes: Client AK / OpenAPI / Cookie
  • API guide - dataset CRUD and batch operations
  • API reference - full signatures for ServicesNamespace / OcrClient / FileClient

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