Skip to content

Commit

Permalink
feat: allow specifying custom items merger for AutoFetchCollection
Browse files Browse the repository at this point in the history
  • Loading branch information
maxnowack committed Nov 11, 2024
1 parent 9c28aa6 commit 6ebfea0
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/replication/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ const Todos = new AutoFetchCollection({
// If a persistence adapter is used, the data is loaded first and will be updated after the server data is fetched
// If the data will be updated, the data will be saved to the persistence adapter and pushed to the server simultaneously
persistence: createLocalStorageAdapter('todos'),

// Optionally you can also specify a mergeItems function to merge items
// if they're returned by multiple fetchQueryItems calls.
mergeItems: (itemA, itemB) => ({ ...itemA, ...itemB }),
})

// You can also observe the loading state of the collection.
Expand Down
5 changes: 4 additions & 1 deletion packages/signaldb/src/AutoFetchCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface AutoFetchOptions<T extends { id: I } & Record<string, any>, I> {
fetchQueryItems: (selector: Selector<T>) => ReturnType<ReplicatedCollectionOptions<T, I>['pull']>,
purgeDelay?: number,
registerRemoteChange?: (onChange: () => Promise<void>) => Promise<void>,
mergeItems?: (itemA: T, itemB: T) => T,
}
export type AutoFetchCollectionOptions<
T extends BaseItem<I>,
Expand All @@ -35,6 +36,7 @@ export default class AutoFetchCollection<
private reactivityAdapter: ReactivityAdapter | null = null
private loadingSignals = new Map<string, Signal<boolean>>()
private isFetchingSignal: Signal<boolean>
private mergeItems: (itemA: T, itemB: T) => T

/**
* @param options {Object} - Options for the collection.
Expand All @@ -54,7 +56,7 @@ export default class AutoFetchCollection<
newItems.push(item)
return
}
newItems[index] = { ...newItems[index], ...item }
newItems[index] = this.mergeItems(newItems[index], item)
})
return newItems
}, []),
Expand All @@ -64,6 +66,7 @@ export default class AutoFetchCollection<
return Promise.resolve()
},
})
this.mergeItems = options.mergeItems ?? ((itemA, itemB) => ({ ...itemA, ...itemB }))
this.purgeDelay = options.purgeDelay ?? 10000 // 10 seconds
this.isFetchingSignal = createSignal(options.reactivity?.create(), false)
if (!triggerRemoteChange) throw new Error('No triggerRemoteChange method found. Looks like your persistence adapter was not registered')
Expand Down

0 comments on commit 6ebfea0

Please sign in to comment.