본문으로 건너뛰기

인터페이스: LocalStorageCollectionConfig<T, TSchema, TKey>

정의 위치: packages/db/src/local-storage.ts:60

localStorage 컬렉션 옵션을 위한 구성 인터페이스입니다

상속​

타입 매개변수​

T​

T extends object = object

컬렉션 항목의 타입입니다.

TSchema​

TSchema 확장 StandardSchemaV1 = never

검증을 위한 스키마 타입

TKey​

TKey extends string | number = string | number

getKey에서 반환되는 키의 타입입니다.

속성​

autoIndex?​

optional autoIndex: "off" | "eager";

정의 위치: packages/db/src/types.ts:641

컬렉션의 자동 인덱싱 모드입니다. 활성화하면 단순한 where 표현식에 대한 인덱스가 자동으로 생성됩니다.

기본값​

"off"

설명​

  • "off": 자동 인덱싱을 사용하지 않습니다(기본값). 번들 크기를 줄이려면 명시적 인덱스를 사용합니다.
  • "eager": subscribeChanges의 단순한 where 표현식에 대한 인덱스를 자동으로 생성합니다. defaultIndexType을 설정해야 합니다.

상속받은 속성​

BaseCollectionConfig.autoIndex


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()

상속받은 속성​

BaseCollectionConfig.compare


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',
// ...
})

상속받은 속성​

BaseCollectionConfig.defaultIndexType


defaultStringCollation?​

optional defaultStringCollation: StringCollationConfig;

정의 위치: packages/db/src/types.ts:812

컬렉션의 데이터를 비교하는 방법을 지정합니다. 백엔드의 데이터 정렬 순서와 일치하도록 구성해야 합니다. 예를 들어 Electric DB 컬렉션을 사용할 때는 이러한 옵션이 데이터베이스의 정렬 설정과 일치해야 합니다.

상속받은 속성​

BaseCollectionConfig.defaultStringCollation


gcTime?​

optional gcTime: number;

정의 위치: packages/db/src/types.ts:620

활성 구독자가 없을 때 컬렉션이 가비지 컬렉션되는 시간(밀리초)입니다. 기본값은 5분(300000ms)입니다.

상속받은 속성​

BaseCollectionConfig.gcTime


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

상속받은 속성​

BaseCollectionConfig.getKey


id?​

optional id: string;

정의 위치: packages/db/src/types.ts:604

상속받은 속성​

BaseCollectionConfig.id


onDelete?​

optional onDelete: DeleteMutationFn<T, TKey, UtilsRecord, any>;

정의 위치: 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
}
}

상속받은 속성​

BaseCollectionConfig.onDelete


onInsert?​

optional onInsert: InsertMutationFn<T, TKey, UtilsRecord, any>;

정의 위치: 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
})
}

상속받은 속성​

BaseCollectionConfig.onInsert


onUpdate?​

optional onUpdate: UpdateMutationFn<T, TKey, UtilsRecord, any>;

정의 위치: 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
}
}

상속받은 속성​

BaseCollectionConfig.onUpdate


parser?​

optional parser: Parser;

정의 위치: packages/db/src/local-storage.ts:86

스토리지와 데이터를 직렬화 및 역직렬화할 때 사용할 파서입니다 기본값은 JSON입니다


schema?​

optional schema: TSchema;

정의 위치: packages/db/src/types.ts:605

상속받은 속성​

BaseCollectionConfig.schema


startSync?​

optional startSync: boolean;

정의 위치: packages/db/src/types.ts:631

컬렉션 생성 시 동기화를 즉시 시작할지 여부입니다. true이면 동기화가 즉시 시작되고, false이면 첫 번째 구독자가 연결될 때 시작됩니다.

참고: startSync=true인 경우에도 활성 구독자가 없으면 컬렉션은 동기화를 일시 중지합니다(일반적으로 컬렉션을 쿼리하는 컴포넌트가 마운트 해제될 때). 새 구독자가 연결되면 동기화를 재개합니다. 이를 통해 일반적인 staleTime/gcTime 동작을 유지합니다.

기본값​

false

상속받은 속성​

BaseCollectionConfig.startSync


storage?​

optional storage: StorageApi;

정의 위치: packages/db/src/local-storage.ts:74

사용할 Storage API입니다(기본값은 window.localStorage입니다) Storage 인터페이스를 구현하는 모든 객체를 사용할 수 있습니다(예: sessionStorage)


storageEventApi?​

optional storageEventApi: StorageEventApi;

정의 위치: packages/db/src/local-storage.ts:80

탭 간 동기화에 사용할 스토리지 이벤트 API입니다(기본값은 window입니다) 스토리지 이벤트에 대해 addEventListener/removeEventListener를 구현하는 모든 객체를 사용할 수 있습니다


storageKey​

storageKey: string;

정의 위치: packages/db/src/local-storage.ts:68

localStorage/sessionStorage에 컬렉션 데이터를 저장할 때 사용할 키입니다


syncMode?​

optional syncMode: SyncMode;

정의 위치: packages/db/src/types.ts:675

컬렉션에 사용할 동기화 모드입니다.

기본값​

eager

설명​

  • eager: 사전 로드 시 모든 데이터를 즉시 동기화합니다
  • on-demand: 컬렉션이 쿼리될 때 증분 스냅샷으로 데이터를 동기화합니다 동기화 모드의 정확한 구현은 동기화 구현에 따라 결정됩니다.

상속받은 속성​

BaseCollectionConfig.syncMode


utils?​

optional utils: UtilsRecord;

정의 위치: packages/db/src/types.ts:814

상속받은 속성​

BaseCollectionConfig.utils