Resources
OcrivaClient เปิดให้ใช้งาน resource object ทั้งหมด 5 รายการ แต่ละ resource รวม API method ที่เกี่ยวข้องไว้ด้วยกัน และจัดการ serialization, authentication และ error mapping ให้คุณโดยอัตโนมัติ
| Resource | Property | Description |
|---|---|---|
| Upload | client.upload | อัปโหลดไฟล์สำหรับการประมวลผล OCR |
| Templates | client.templates | สร้างและจัดการ extraction template |
| Projects | client.projects | ดึงข้อมูล project ที่เข้าถึงได้ |
| Processing History | client.processingHistory | เข้าถึงผลลัพธ์และสถิติ OCR |
| Batch | client.batch | อัปโหลดและติดตามหลายไฟล์พร้อมกัน |
Upload
อัปโหลดไฟล์
อัปโหลดไฟล์เดียวสำหรับการประมวลผล OCR SDK รองรับ browser File, Blob หรือ Node.js Buffer / Uint8Array
async file(
file: File | Blob | Uint8Array,
params: UploadFileParams,
): Promise<UploadResponse>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
file | File | Blob | Uint8Array | Yes | ไฟล์ binary ที่จะอัปโหลด |
params.fileName | string | Yes | ชื่อที่แสดงของไฟล์ |
params.fileType | FileType | Yes | ประเภทหลัก: 'pdf', 'image' หรือ 'document' |
params.fileSize | string | Yes | ขนาดไฟล์ในหน่วยไบต์ในรูปแบบ string |
params.mimeType | string | Yes | MIME type เช่น 'application/pdf' |
params.projectId | string | Yes | Project ที่จะเชื่อมกับการอัปโหลดนี้ |
params.templateId | string | No | Template ที่จะใช้ระหว่างการประมวลผล |
params.batchId | string | No | เพิ่มไฟล์นี้เข้า batch ที่มีอยู่แล้ว |
params.uploadType | string | No | hint ประเภทการอัปโหลด (optional) |
params.metadata | Record<string, unknown> | No | metadata แบบ key-value ที่กำหนดเอง |
Examples
อัปโหลด File object จาก browser <input>:
import { OcrivaClient } from '@ocriva/sdk';
const client = new OcrivaClient({ apiKey: process.env.OCRIVA_API_KEY! });
async function handleFileInput(file: File) {
const result = await client.upload.file(file, {
fileName: file.name,
fileType: 'pdf',
fileSize: String(file.size),
mimeType: file.type,
projectId: 'proj_abc123',
});
console.log('Upload ID:', result.id);
console.log('Status:', result.status);
}อัปโหลด Buffer ใน Node.js:
import { readFileSync } from 'node:fs';
const buffer = readFileSync('./receipt.jpg');
const result = await client.upload.file(buffer, {
fileName: 'receipt.jpg',
fileType: 'image',
fileSize: String(buffer.byteLength),
mimeType: 'image/jpeg',
projectId: 'proj_abc123',
templateId: 'tmpl_xyz789',
});อัปโหลด Blob พร้อม custom metadata:
const response = await fetch('https://example.com/document.pdf');
const blob = await response.blob();
const result = await client.upload.file(blob, {
fileName: 'document.pdf',
fileType: 'pdf',
fileSize: String(blob.size),
mimeType: 'application/pdf',
projectId: 'proj_abc123',
metadata: { source: 'crm', customerId: 'cust_999' },
});Response shape (UploadResponse)
{
id: string;
fileName: string;
fileUrl: string;
publicUrl: string;
filePath: string;
fileSize: string;
mimeType: string;
status: 'uploaded' | 'processing' | 'completed' | 'failed';
templateId?: string;
projectId: string;
uploadedAt: string;
userId: string;
organizationId?: string;
bucketName?: string;
}Templates
รายการ Templates
แสดงรายการ template ทั้งหมดที่ token ปัจจุบันเข้าถึงได้
async list(params?: ListTemplatesParams): Promise<Template[]>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
params.projectId | string | No | กรองตาม project ID |
params.page | number | No | หมายเลขหน้า (เริ่มต้นที่ 1) |
params.limit | number | No | จำนวน item ต่อหน้า |
// List all templates
const templates = await client.templates.list();
// Filter by project with pagination
const page1 = await client.templates.list({
projectId: 'proj_abc123',
page: 1,
limit: 20,
});
console.log(`Found ${page1.length} templates`);สร้าง Template
สร้าง extraction template ใหม่
async create(params: CreateTemplateParams): Promise<Template>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
params.name | string | Yes | ชื่อ template |
params.description | string | Yes | คำอธิบาย template |
params.templateSchema | Record<string, unknown> | Yes | JSON schema ที่กำหนดฟิลด์ที่จะดึงข้อมูล |
params.projectId | string | Yes | Project ที่ template นี้เป็นของ |
params.instructions | string | No | คำแนะนำ AI assistant ที่กำหนดเอง |
const template = await client.templates.create({
name: 'Invoice Template',
description: 'Extracts line items, totals, and vendor information from invoices',
projectId: 'proj_abc123',
templateSchema: {
type: 'object',
properties: {
invoiceNumber: { type: 'string', description: 'Invoice number' },
vendorName: { type: 'string', description: 'Vendor or supplier name' },
totalAmount: { type: 'number', description: 'Total invoice amount' },
dueDate: { type: 'string', description: 'Payment due date (YYYY-MM-DD)' },
lineItems: {
type: 'array',
items: {
type: 'object',
properties: {
description: { type: 'string' },
quantity: { type: 'number' },
unitPrice: { type: 'number' },
},
},
},
},
},
instructions: 'Extract all monetary values as numbers without currency symbols.',
});
console.log('Template ID:', template.templateId);อัปเดต Template
อัปเดต template ที่มีอยู่ ทุกฟิลด์ยกเว้น projectId เป็น optional
async update(id: string, params: UpdateTemplateParams): Promise<Template>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Template ID ที่จะอัปเดต |
params.projectId | string | Yes | Project ID (ใช้กำหนดขอบเขตการอัปเดต) |
params.name | string | No | ชื่อ template ใหม่ |
params.description | string | No | คำอธิบายใหม่ |
params.templateSchema | Record<string, unknown> | No | JSON schema ที่อัปเดต |
params.instructions | string | No | คำแนะนำ AI ที่อัปเดต |
// Partial update — only change the instructions
const updated = await client.templates.update('tmpl_xyz789', {
projectId: 'proj_abc123',
instructions: 'Always return amounts in USD. If currency is not USD, convert it.',
});ลบ Template
Soft-delete template โดย template จะไม่ active และไม่สามารถใช้กับการอัปโหลดใหม่ได้
async delete(id: string): Promise<void>await client.templates.delete('tmpl_xyz789');
// Returns void — no response bodyอัปโหลด Data File
แนบไฟล์ข้อมูล (JSON, Markdown หรือ plain text) เข้ากับ template AI ใช้ไฟล์นี้เป็น context เพิ่มเติมระหว่างการดึงข้อมูล
async uploadFile(templateId: string, file: File | Blob): Promise<Template>import { readFileSync } from 'node:fs';
// Attach a reference schema as a Markdown file
const mdContent = readFileSync('./field-guide.md');
const blob = new Blob([mdContent], { type: 'text/markdown' });
const updatedTemplate = await client.templates.uploadFile('tmpl_xyz789', blob);
console.log('Attached files:', updatedTemplate.templateId);ลบ Data File
ลบไฟล์ข้อมูลที่แนบออกจาก template
async deleteFile(templateId: string, fileId: string): Promise<Template>const updatedTemplate = await client.templates.deleteFile(
'tmpl_xyz789',
'file_abc456',
);Projects
รายการ Projects
แสดงรายการ project ที่ token ปัจจุบันเข้าถึงได้
- Project token: คืน project เดียวที่ token ผูกไว้
- Organization token: คืน project ทั้งหมดใน organization
async list(params?: ListProjectsParams): Promise<Project[]>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
params.projectId | string | No | กรองเฉพาะ project ที่ระบุ (สำหรับ organization token) |
// List all accessible projects
const projects = await client.projects.list();
for (const project of projects) {
console.log(`${project.id}: ${project.name} (active: ${project.isActive})`);
}
// Scope to one project using an organization token
const filtered = await client.projects.list({ projectId: 'proj_abc123' });Response shape (Project)
{
id: string;
name: string;
description?: string;
organizationId: string;
isActive: boolean;
createdAt: string;
updatedAt: string;
}Processing History
รายการประวัติการประมวลผล
แสดงรายการ processing history record พร้อมตัวกรองและ pagination ตามต้องการ
async list(
params?: ListProcessingHistoryParams,
): Promise<PaginatedResponse<ProcessingHistory>>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
params.projectId | string | No | Project ID (จำเป็นสำหรับ organization token) |
params.status | ProcessingStatus | No | กรองตาม status |
params.templateId | string | No | กรองตาม template |
params.priority | ProcessingPriority | No | กรองตาม priority |
params.search | string | No | ค้นหาตามชื่อไฟล์หรือชื่อ template |
params.fromDate | string | No | ตัวกรองวันเริ่มต้น (YYYY-MM-DD) |
params.toDate | string | No | ตัวกรองวันสิ้นสุด (YYYY-MM-DD) |
params.batchId | string | No | กรองตาม batch ID |
params.page | number | No | หมายเลขหน้า (เริ่มต้นที่ 1) |
params.limit | number | No | จำนวน item ต่อหน้า |
// List completed records for a project
const result = await client.processingHistory.list({
projectId: 'proj_abc123',
status: 'completed',
page: 1,
limit: 50,
});
console.log(`Page ${result.pagination.page} of ${result.pagination.pages}`);
console.log(`Total records: ${result.pagination.total}`);
for (const record of result.data) {
console.log(`${record.id}: ${record.fileName} — ${record.status}`);
}
// Filter by date range
const recent = await client.processingHistory.list({
projectId: 'proj_abc123',
fromDate: '2026-03-01',
toDate: '2026-03-31',
});
// Filter by template
const byTemplate = await client.processingHistory.list({
projectId: 'proj_abc123',
templateId: 'tmpl_xyz789',
status: 'failed',
});ดูรายละเอียด
ดึง processing history record เดียวตาม ID
async get(id: string, projectId?: string): Promise<ProcessingHistory>const record = await client.processingHistory.get(
'hist_abc123',
'proj_abc123', // required for organization tokens
);
console.log('Status:', record.status);
console.log('Result:', record.processingResult);Export ผลลัพธ์
ดาวน์โหลดผลลัพธ์การประมวลผลในรูปแบบ Blob ตามรูปแบบที่ระบุ
async getResult(id: string, params?: ExportResultParams): Promise<Blob>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | ID ของ processing history record |
params.format | string | No | รูปแบบ output: 'json', 'text', 'xml', 'html', 'csv', 'pdf', 'docx' |
params.projectId | string | No | Project ID (จำเป็นสำหรับ organization token) |
// Download as JSON and parse
const blob = await client.processingHistory.getResult('hist_abc123', {
format: 'json',
projectId: 'proj_abc123',
});
const data = JSON.parse(await blob.text());
console.log(data);
// Download as PDF and save to disk (Node.js)
import { writeFileSync } from 'node:fs';
const pdfBlob = await client.processingHistory.getResult('hist_abc123', {
format: 'pdf',
projectId: 'proj_abc123',
});
const arrayBuffer = await pdfBlob.arrayBuffer();
writeFileSync('./result.pdf', Buffer.from(arrayBuffer));
// Download as CSV
const csvBlob = await client.processingHistory.getResult('hist_abc123', {
format: 'csv',
projectId: 'proj_abc123',
});
const csv = await csvBlob.text();
console.log(csv);ดูสถิติ
ดึงสถิติการประมวลผลแบบรวมสำหรับ project
async stats(params: { projectId: string }): Promise<ProcessingHistoryStats>const stats = await client.processingHistory.stats({
projectId: 'proj_abc123',
});
console.log('Total:', stats.total);
console.log('Pending:', stats.pending);
console.log('Processing:', stats.processing);
console.log('Completed:', stats.completed);
console.log('Failed:', stats.failed);Response shape (ProcessingHistoryStats)
{
total: number;
pending: number;
processing: number;
completed: number;
failed: number;
}Batch
ใช้ batch resource เพื่ออัปโหลดและติดตามหลายไฟล์ในรูปแบบ job เดียว แต่ละไฟล์ประมวลผลแยกกัน โดย batch record ติดตามความคืบหน้าโดยรวมและช่วยให้คุณ export ผลลัพธ์ทั้งหมดได้ในครั้งเดียว
อัปโหลด Batch
อัปโหลดหลายไฟล์เป็น batch เดียว รองรับสูงสุด 50 ไฟล์ต่อ call
async upload(
files: (File | Blob)[],
params: BatchUploadParams,
): Promise<Batch>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
files | (File | Blob)[] | Yes | Array ของไฟล์ที่จะอัปโหลด (สูงสุด 50) |
params.projectId | string | Yes | Project ที่จะเชื่อมกับ batch นี้ |
params.templateId | string | No | Template ที่จะใช้กับทุกไฟล์ |
params.name | string | No | ชื่อ batch (สร้างอัตโนมัติหากไม่ระบุ) |
params.metadata | Record<string, unknown> | No | metadata แบบ key-value ที่กำหนดเอง |
import { readFileSync } from 'node:fs';
const files = ['invoice-01.pdf', 'invoice-02.pdf', 'invoice-03.pdf'].map(
(name) => {
const buffer = readFileSync(`./${name}`);
return new File([buffer], name, { type: 'application/pdf' });
},
);
const batch = await client.batch.upload(files, {
projectId: 'proj_abc123',
templateId: 'tmpl_xyz789',
name: 'March Invoices',
metadata: { month: 'march', year: '2026' },
});
console.log('Batch ID:', batch.id);
console.log('Total files:', batch.totalFiles);
console.log('Status:', batch.status);รายการ Batches
แสดงรายการ batch พร้อมตัวกรองและ pagination ตามต้องการ
async list(params?: ListBatchParams): Promise<PaginatedResponse<Batch>>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
params.projectId | string | No | Project ID (จำเป็นสำหรับ organization token) |
params.status | BatchStatus | No | กรองตาม status |
params.page | number | No | หมายเลขหน้า (เริ่มต้นที่ 1) |
params.limit | number | No | จำนวน item ต่อหน้า |
const result = await client.batch.list({
projectId: 'proj_abc123',
status: 'completed',
page: 1,
limit: 10,
});
console.log(`Total batches: ${result.pagination.total}`);
for (const batch of result.data) {
console.log(`${batch.id}: ${batch.name} — ${batch.progress}% complete`);
}รายละเอียด Batch
ดึง batch เดียวตาม ID พร้อมความคืบหน้าปัจจุบัน
async get(batchId: string): Promise<Batch>const batch = await client.batch.get('batch_abc123');
console.log('Status:', batch.status);
console.log('Progress:', batch.progress, '%');
console.log(`${batch.completedFiles} / ${batch.totalFiles} files done`);
console.log('Failed:', batch.failedFiles);Response shape (Batch)
{
id: string;
name: string;
projectId: string;
organizationId: string;
userId: string;
templateId?: string;
templateName?: string;
totalFiles: number;
completedFiles: number;
failedFiles: number;
status: BatchStatus; // 'uploading' | 'processing' | 'completed' | 'partially_failed' | 'failed'
uploadIds: string[];
processingHistoryIds: string[];
progress: number; // 0–100
metadata?: Record<string, unknown>;
createdAt: string;
updatedAt: string;
}Export ผลลัพธ์ Batch
Export ผลลัพธ์การประมวลผลที่เสร็จแล้วทั้งหมดของ batch เป็นไฟล์เดียว
async exportResults(batchId: string, params: ExportBatchParams): Promise<Blob>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
batchId | string | Yes | Batch ID |
params.format | string | Yes | รูปแบบ export: 'json', 'csv', 'text', 'xml', 'pdf', 'docx' |
// Export as JSON and parse
const blob = await client.batch.exportResults('batch_abc123', {
format: 'json',
});
const results = JSON.parse(await blob.text());
console.log(`Exported ${results.length} results`);
// Export as CSV and save (Node.js)
import { writeFileSync } from 'node:fs';
const csvBlob = await client.batch.exportResults('batch_abc123', {
format: 'csv',
});
writeFileSync('./batch-results.csv', Buffer.from(await csvBlob.arrayBuffer()));