인터페이스: BaseCollectionConfig<T, TKey, TSchema, TUtils, TReturn>
정의 위치: packages/db/src/types.ts:591
확장 대상
타입 매개변수
T
T extends object = Record<string, unknown>
TKey
TKey 확장 string | number = string | number
TSchema
TSchema 확장 StandardSchemaV1 = never
TUtils
TUtils extends UtilsRecord = UtilsRecord
TReturn
TReturn = any
속성
autoIndex?
optional autoIndex: "off" | "eager";
정의 위치: packages/db/src/types.ts:641
컬렉션의 자동 인덱싱 모드입니다. 활성화하면 단순한 where 표현식에 대한 인덱스가 자동으로 생성됩니다.
기본값
"off"
설명
- "off": 자동 인덱싱을 사용하지 않습니다(기본값). 번들 크기를 줄이려면 명시적 인덱스를 사용합니다.
- "eager": subscribeChanges의 단순한 where 표현식에 대한 인덱스를 자동으로 생성합니다. defaultIndexType을 설정해야 합니다.
compare()?
optional compare: (x, y) => number;
정의 위치: packages/db/src/types.ts:666
두 항목을 비교하는 선택적 함수입니다. 컬렉션의 항목 순서를 지정하는 데 사용됩니다.
매개변수
x
T
비교할 첫 번째 항목입니다
y
T
비교할 두 번째 항목입니다
반환값
number
항목 순서를 나타내는 숫자입니다
예제
// For a collection with a 'createdAt' field
compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
defaultIndexType?
optional defaultIndexType: IndexConstructor<TKey>;
정의 위치: packages/db/src/types.ts:655
명시적 유형 없이 인덱스를 생성할 때 사용할 기본 인덱스 유형입니다. 자동 인덱싱에 필요합니다. '@tanstack/db'에서 가져옵니다.
예제
import { BasicIndex } from '@tanstack/db'
const collection = createCollection({
defaultIndexType: BasicIndex,
autoIndex: 'eager',
// ...
})
defaultStringCollation?
optional defaultStringCollation: StringCollationConfig;
정의 위치: packages/db/src/types.ts:812
컬렉션의 데이터를 비교하는 방법을 지정합니다. 백엔드의 데이터 정렬 순서와 일치하도록 구성해야 합니다. 예를 들어 Electric DB 컬렉션을 사용할 때는 이러한 옵션이 데이터베이스의 정렬 설정과 일치해야 합니다.
gcTime?
optional gcTime: number;
정의 위치: packages/db/src/types.ts:620
활성 구독자가 없을 때 컬렉션이 가비지 컬렉션되는 시간(밀리초)입니다. 기본값은 5분(300000ms)입니다.
getKey()
getKey: (item) => TKey;
정의 위치: packages/db/src/types.ts:615
객체에서 ID를 추출하는 함수입니다. 이제 ID만 허용하는 업데이트/삭제 작업에 필요합니다.
매개변수
item
T
ID를 추출할 항목입니다
반환값
TKey
항목의 ID 문자열입니다
예제
// For a collection with a 'uuid' field as the primary key
getKey: (item) => item.uuid
id?
optional id: string;
정의 위치: packages/db/src/types.ts:604
onDelete?
optional onDelete: DeleteMutationFn<T, TKey, TUtils, TReturn>;
정의 위치: packages/db/src/types.ts:804
삭제 작업 전에 호출되는 선택적 비동기 핸들러 함수
매개변수
트랜잭션 및 컬렉션 정보가 포함된 객체
반환값
모든 값을 확인하는 Promise입니다
예제
// Basic delete handler
onDelete: async ({ transaction, collection }) => {
const deletedKey = transaction.mutations[0].key
await api.deleteTodo(deletedKey)
}
// Delete handler with multiple items
onDelete: async ({ transaction, collection }) => {
const keysToDelete = transaction.mutations.map(m => m.key)
await api.deleteTodos(keysToDelete)
}
// Delete handler with confirmation
onDelete: async ({ transaction, collection }) => {
const mutation = transaction.mutations[0]
const shouldDelete = await confirmDeletion(mutation.original)
if (!shouldDelete) {
throw new Error('Delete cancelled by user')
}
await api.deleteTodo(mutation.original.id)
}
// Delete handler with optimistic rollback
onDelete: async ({ transaction, collection }) => {
const mutation = transaction.mutations[0]
try {
await api.deleteTodo(mutation.original.id)
} catch (error) {
// Transaction will automatically rollback optimistic changes
console.error('Delete failed, rolling back:', error)
throw error
}
}
onInsert?
optional onInsert: InsertMutationFn<T, TKey, TUtils, TReturn>;
정의 위치: packages/db/src/types.ts:717
삽입 작업 전에 호출되는 선택적 비동기 핸들러 함수
매개변수
트랜잭션 및 컬렉션 정보가 포함된 객체
반환값
모든 값을 확인하는 Promise입니다
예제
// Basic insert handler
onInsert: async ({ transaction, collection }) => {
const newItem = transaction.mutations[0].modified
await api.createTodo(newItem)
}
// Insert handler with multiple items
onInsert: async ({ transaction, collection }) => {
const items = transaction.mutations.map(m => m.modified)
await api.createTodos(items)
}
// Insert handler with error handling
onInsert: async ({ transaction, collection }) => {
try {
const newItem = transaction.mutations[0].modified
const result = await api.createTodo(newItem)
return result
} catch (error) {
console.error('Insert failed:', error)
throw error // This will cause the transaction to fail
}
}
// Insert handler with metadata
onInsert: async ({ transaction, collection }) => {
const mutation = transaction.mutations[0]
await api.createTodo(mutation.modified, {
source: mutation.metadata?.source,
timestamp: mutation.createdAt
})
}
onUpdate?
optional onUpdate: UpdateMutationFn<T, TKey, TUtils, TReturn>;
정의 위치: packages/db/src/types.ts:761
업데이트 작업 전에 호출되는 선택적 비동기 핸들러 함수
매개변수
트랜잭션 및 컬렉션 정보가 포함된 객체
반환값
모든 값을 확인하는 Promise입니다
예제
// Basic update handler
onUpdate: async ({ transaction, collection }) => {
const updatedItem = transaction.mutations[0].modified
await api.updateTodo(updatedItem.id, updatedItem)
}
// Update handler with partial updates
onUpdate: async ({ transaction, collection }) => {
const mutation = transaction.mutations[0]
const changes = mutation.changes // Only the changed fields
await api.updateTodo(mutation.original.id, changes)
}
// Update handler with multiple items
onUpdate: async ({ transaction, collection }) => {
const updates = transaction.mutations.map(m => ({
id: m.key,
changes: m.changes
}))
await api.updateTodos(updates)
}
// Update handler with optimistic rollback
onUpdate: async ({ transaction, collection }) => {
const mutation = transaction.mutations[0]
try {
await api.updateTodo(mutation.original.id, mutation.changes)
} catch (error) {
// Transaction will automatically rollback optimistic changes
console.error('Update failed, rolling back:', error)
throw error
}
}
schema?
optional schema: TSchema;
정의 위치: packages/db/src/types.ts:605
startSync?
optional startSync: boolean;
정의 위치: packages/db/src/types.ts:631
컬렉션 생성 시 동기화를 즉시 시작할지 여부입니다. true이면 동기화가 즉시 시작되고, false이면 첫 번째 구독자가 연결될 때 시작됩니다.
참고: startSync=true인 경우에도 활성 구독자가 없으면 컬렉션은 동기화를 일시 중지합니다(일반적으로 컬렉션을 쿼리하는 컴포넌트가 마운트 해제될 때). 새 구독자가 연결되면 동기화를 재개합니다. 이를 통해 일반적인 staleTime/gcTime 동작을 유지합니다.
기본값
false
syncMode?
optional syncMode: SyncMode;
정의 위치: packages/db/src/types.ts:675
컬렉션에 사용할 동기화 모드입니다.
기본값
eager
설명
eager: 프리로드 시 모든 데이터를 즉시 동기화합니다on-demand: 컬렉션을 쿼리할 때 증분 스냅샷으로 데이터를 동기화합니다 동기화 모드의 정확한 구현은 동기화 구현에 따라 결정됩니다.
utils?
optional utils: TUtils;
정의 위치: packages/db/src/types.ts:814