메인 콘텐츠로 건너뛰기

Smart Tables SDK

SmartTablesSDK는 고급 쿼리링, 필터링, 정렬 및 데이터 조작 기능을 포함한 구조화된 데이터 테이블 관리에 대한 포괄적인 솔루션을 제공합니다. 사용자 지정 보기, 데이터 가져오기/내보내기 및 AI 기반 데이터 처리를 지원하는 강력한 데이터 관리 애플리케이션을 쉽게 구축하세요.

설치​

npm install @odin-ai-staging/sdk

빠른 시작​

이 예시에서는 EKB API를 통해 SmartTablesSDK를 사용하여 프로그래밍 방식으로 구조화된 데이터 테이블을 만들고 관리하는 방법을 알아봅니다. API 자격 증명으로 SDK를 초기화한 다음 간단한 워크플로우를 따라 기능적인 데이터베이스를 구축합니다.

import { SmartTablesSDK } from '@odin-ai-staging/sdk';

// SDK 초기화
const smartTablesSDK = new SmartTablesSDK({
baseUrl: 'https://your-api-endpoint.com/',
projectId: 'your-project-id',
apiKey: 'your-api-key',
apiSecret: 'your-api-secret'
});

// 빠른 예시: 테이블 만들고 데이터 추가
async function quickExample() {
// 새 테이블 만들기
const table = await smartTablesSDK.createTable(
'고객 데이터베이스',
'고객 정보 관리'
);

// 열 추가
await smartTablesSDK.addColumn(table.id, {
name: 'name',
type: 'text',
description: '고객 이름'
});

await smartTablesSDK.addColumn(table.id, {
name: 'email',
type: 'email',
description: '고객 이메일 주소'
});

// 데이터 추가
await smartTablesSDK.addRow(table.id, {
name: '홍길동',
email: 'hong@example.com'
});

// 데이터 쿼리
const results = await smartTablesSDK.queryTable(table.id, {
filters: [{ column: 'name', operator: 'contains', value: '홍' }],
pagination: { limit: 10, page: 1 }
});

console.log('쿼리 결과:', results.data);
}

구성​

SmartTablesSDKConfig 인터페이스​

interface SmartTablesSDKConfig {
baseUrl: string; // API 엔드포인트 URL
projectId: string; // 프로젝트 식별자
apiKey?: string; // 인증용 API 키
apiSecret?: string; // 인증용 API 시크릿
accessToken?: string; // 웹 앱 사용을 위한 액세스 토큰
}

핵심 개념​

SmartTable​

SmartTable은 스키마, 메타데이터 및 데이터 관리 기능을 가진 구조화된 데이터 테이블을 나타냅니다.

interface SmartTable {
id: string; // 고유 테이블 식별자
project_id: string; // 이 테이블이 속한 프로젝트
title: string; // 테이블 표시 이름
description: string; // 테이블 설명
schema: SmartTableColumn[]; // 열 정의
table_name: string; // 내부 테이블 이름
created_at?: number; // 생성 타임스탬프
updated_at?: number; // 마지막 업데이트 타임스탬프
}

SmartTableColumn​

테이블 열의 구조와 속성을 정의합니다.

interface SmartTableColumn {
name: string; // 열 이름
type: ColumnType; // 데이터 유형
description?: string; // 열 설명
notNull?: boolean; // 필수 필드
unique?: boolean; // 고유 제약 조건
defaultValue?: string | number | boolean | null; // 기본 값
options?: Record<string, unknown>; // 추가 옵션
}

type ColumnType = 'text' | 'number' | 'boolean' | 'date' | 'email' | 'url' | 'json';

필터링 및 쿼리링​

여러 연산자와 정렬 옵션이 포함된 고급 필터링 시스템.

interface TableFilter {
column: string;
operator: FilterOperator;
value: string | number | boolean | null;
}

type FilterOperator = 'eq' | 'ne' | 'gt' | 'lt' | 'gte' | 'lte' | 'contains' | 'startswith' | 'endswith';

interface TableSort {
column: string;
direction: 'asc' | 'desc';
}

interface TablePagination {
page?: number;
limit?: number;
search?: string;
}

테이블 관리​

getAllTables()​

프로젝트의 모든 테이블을 가져옵니다.

async getAllTables(): Promise<SmartTable[]>

예시:

const tables = await smartTablesSDK.getAllTables();
tables.forEach(table => {
console.log(`테이블: ${table.title} (${table.id})`);
console.log(`열 수: ${table.schema.length}`);
});

getTable(tableId)​

ID로 특정 테이블을 가져옵니다.

async getTable(tableId: string): Promise<SmartTable>

createTable(title, description, metadata?)​

새 테이블을 만듭니다.

async createTable(
title: string,
description: string,
metadata?: Record<string, unknown>
): Promise<SmartTable>

updateTable(tableId, title, description?, metadata?)​

테이블 메타데이터를 업데이트합니다.

deleteTable(tableId)​

테이블과 모든 데이터를 영구적으로 삭제합니다.

열 작업​

addColumn(tableId, column)​

테이블에 새 열을 추가합니다.

async addColumn(tableId: string, column: SmartTableColumn): Promise<void>

예시:

// 텍스트 열 추가
await smartTablesSDK.addColumn('table_123', {
name: 'product_name',
type: 'text',
description: '상품 이름',
notNull: true
});

// 기본값이 있는 숫자 열 추가
await smartTablesSDK.addColumn('table_123', {
name: 'price',
type: 'number',
description: 'USD 단위 상품 가격',
defaultValue: 0,
notNull: true
});

updateColumn(tableId, columnName, updates)​

열 속성을 업데이트합니다.

deleteColumn(tableId, columnName)​

테이블에서 열을 제거합니다.

데이터 작업​

addRow(tableId, data)​

테이블에 새 행을 추가합니다.

async addRow(tableId: string, data: Record<string, any>): Promise<any>

예시:

const newRow = await smartTablesSDK.addRow('table_123', {
product_name: '무선 헤드폰',
price: 99.99,
supplier_email: 'supplier@example.com',
in_stock: true
});

console.log('새 행 ID:', newRow.id);

updateRow(tableId, rowId, columnName, newValue)​

테이블의 특정 셀을 업데이트합니다.

deleteRow(tableId, rowId)​

테이블에서 행을 삭제합니다.

쿼리링 및 필터링​

queryTable(tableId, options?)​

고급 필터링, 정렬 및 페이지네이션으로 테이블 데이터를 쿼리합니다.

예시:

기본 쿼리​

const results = await smartTablesSDK.queryTable('table_123');
console.log('모든 데이터:', results.data);

필터링된 쿼리​

const results = await smartTablesSDK.queryTable('table_123', {
filters: [
{ column: 'price', operator: 'gte', value: 50 },
{ column: 'in_stock', operator: 'eq', value: true },
{ column: 'product_name', operator: 'contains', value: '헤드폰' }
]
});

페이지네이션이 포함된 정렬된 쿼리​

const results = await smartTablesSDK.queryTable('table_123', {
sort: [
{ column: 'price', direction: 'desc' },
{ column: 'product_name', direction: 'asc' }
],
pagination: {
page: 2,
limit: 20,
search: '무선'
}
});

console.log(`${results.total}개 항목을 찾았습니다`);
console.log(`페이지 ${results.page} / ${Math.ceil(results.total / results.limit)}`);

데이터 가져오기/내보내기​

importTable(title, description, columnMappings, file)​

CSV 또는 Excel 파일에서 데이터를 가져옵니다.

async importTable(
title: string,
description: string,
columnMappings: ColumnMapping[],
file: File
): Promise<ImportResult>

예시:

const fileInput = document.getElementById('csvFile') as HTMLInputElement;
const file = fileInput.files[0];

const columnMappings: ColumnMapping[] = [
{ sourceColumn: 'Name', targetColumn: 'product_name', dataType: 'text' },
{ sourceColumn: 'Price', targetColumn: 'price', dataType: 'number' },
{ sourceColumn: 'Email', targetColumn: 'supplier_email', dataType: 'email' }
];

const result = await smartTablesSDK.importTable(
'가져온 상품',
'CSV에서 가져온 상품',
columnMappings,
file
);

console.log(`${result.rows_imported}행을 가져왔습니다`);

AI 기반 기능​

computeRowColumns(dataTypeId, rowId, columnNames?)​

특정 행 열에 대한 AI 계산을 트리거합니다.

computeAllRows(dataTypeId)​

테이블의 모든 행에 대한 AI 계산을 트리거합니다.

예시:

const result = await smartTablesSDK.computeAllRows('table_123');
console.log(`${result.total_rows_processed}행을 처리했습니다`);
console.log(`${result.total_columns_updated}열을 업데이트했습니다`);

오류 처리​

SmartTablesSDK는 다른 SDK 컴포넌트와 동일한 오류 처리를 사용합니다:

try {
const table = await smartTablesSDK.createTable('내 테이블', '설명');
} catch (error) {
if (error instanceof APIError) {
console.error(`API 오류 ${error.status}: ${error.message}`);
} else {
console.error('예상치 못한 오류:', error);
}
}

모범 사례​

효율적인 쿼리링​

  • 대용량 데이터세트에 페이지네이션 사용
  • 데이터 전송을 줄이기 위해 필터 적용
  • 가능한 경우 여러 작업 결합
// 좋음: 필터와 페이지네이션이 포함된 효율적인 쿼리
const results = await smartTablesSDK.queryTable(tableId, {
filters: [{ column: 'status', operator: 'eq', value: 'active' }],
pagination: { limit: 50, page: 1 },
sort: [{ column: 'created_at', direction: 'desc' }]
});

스키마 설계​

  • 적절한 열 유형 정의
  • 제약 조건(notNull, unique)을 적절히 사용
  • 의미 있는 설명 제공
// 좋음: 잘 정의된 열 스키마
await smartTablesSDK.addColumn(tableId, {
name: 'email',
type: 'email',
description: '고객 이메일 주소',
notNull: true,
unique: true
});

오류 처리 및 검증​

  • 항상 우아하게 오류를 처리합니다
  • 작업 전에 데이터를 검증합니다
  • 관련 작업에 트랜잭션을 사용합니다
async function safeTableOperation(tableId: string, data: any) {
try {
if (!data.email || !data.email.includes('@')) {
throw new Error('잘못된 이메일 형식');
}
const result = await smartTablesSDK.addRow(tableId, data);
return result;
} catch (error) {
console.error('작업 실패:', error);
if (error.message.includes('unique constraint')) {
throw new Error('이미 존재하는 이메일');
}
throw error;
}
}