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
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:
| authMode | OCR route | File route | Description |
|---|---|---|---|
cookie | GET /api/ocr/recognize-text | /api/common/uploadFile, /api/common/queryFileUrl | WebAPI, carries the user's Cookie |
client-ak | POST /client/ocr | /client/uploadFile, /client/queryFileUrl | Client API, carries X-User-AK |
openapi | ❌ throws OCR_AUTH_MODE_UNSUPPORTED | ❌ throws FILE_AUTH_MODE_UNSUPPORTED | No 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
client.services.ocr.recognize(request: OcrRecognizeRequest): Promise<OcrRecognizeResponse>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.
OcrType | Description |
|---|---|
General | General-purpose text recognition |
Invoice | VAT invoice |
Advanced | High-precision full-text recognition |
AdvancedCoordinate | High precision (with coordinates) |
AdvancedGeneral | High-precision general |
IdCard | ID card |
BankCard | Bank card |
BusinessLicense | Business license |
DrivingLicense | Driver's license |
CarNumber | License plate |
Table | Table |
Example: Browser / Cookie scenario
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)
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
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 torecognize().
📎 File Service: client.services.file
Upload: upload()
client.services.file.upload(request: FileUploadRequest): Promise<FileUploadResponse>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):
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):
const uploaded = await client.services.file.upload({
file: new Blob([buffer], { type: "application/pdf" }),
fileName: "invoice.pdf",
});Response:
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()
client.services.file.queryUrl(request: FileQueryUrlRequest): Promise<FileUrlResponse>interface FileQueryUrlRequest {
filePath: string; // upload() 返回的 filePath(必填)
download?: boolean; // true 返回下载 URL,默认 false(预览 URL)
longTerm?: boolean; // 是否申请长期 URL,默认 false
options?: ServiceRequestOptions;
}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
| Field | Use for | Lifetime |
|---|---|---|
filePath | A stable reference to store in business fields; swap it for a URL whenever needed | Long-term |
fileUrl | Temporary previews, OCR input, short-lived consumption | Short-term |
longTerm: true | Request only when the content must be displayed long-term via URL alone | Long-term |
💡 Recommended: store only
filePathin your business tables; callqueryUrl()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:
| code | Triggered when | Key description fields |
|---|---|---|
OCR_URL_REQUIRED | url is empty | field: "url" |
OCR_TYPE_UNSUPPORTED | type is not in OCR_TYPES | supportedTypes |
OCR_AUTH_MODE_UNSUPPORTED | OCR is called in OpenAPI mode | supportedAuthModes: ["cookie","client-ak"] |
FILE_REQUIRED | file is not a Blob/File | field: "file" |
FILE_PATH_REQUIRED | filePath passed to queryUrl is empty | field: "filePath" |
FILE_AUTH_MODE_UNSUPPORTED | File service is called in OpenAPI mode | supportedAuthModes: ["cookie","client-ak"] |
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