Skip to content

Commit

Permalink
fix: rebuild indices after collection instantiation
Browse files Browse the repository at this point in the history
this enables seeding the collection with a memory adapater that already has data in it
see #626 (reply in thread)
  • Loading branch information
maxnowack committed Mar 30, 2024
1 parent 719423f commit e8d1a33
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/signaldb/__tests__/Collection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,4 +464,14 @@ describe('Collection', () => {
emitSpy.mockRestore()
})
})

describe('misc', () => {
it('should seed the collection with initial data from the memory adapter', () => {
const col = new Collection<{ id: string, name: string }>({
memory: createMemoryAdapter([{ id: '1', name: 'John' }]),
})

expect(col.findOne({ id: '1' })).toEqual({ id: '1', name: 'John' })
})
})
})
6 changes: 6 additions & 0 deletions packages/signaldb/src/Collection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export default class Collection<T extends BaseItem<I> = BaseItem, I = any, U = T
createExternalIndex('id', this.idIndex),
...(this.options.indices || []),
]
this.rebuildIndices()
if (this.options.persistence) {
const persistenceAdapter = this.options.persistence
this.persistenceAdapter = persistenceAdapter
Expand Down Expand Up @@ -263,6 +264,11 @@ export default class Collection<T extends BaseItem<I> = BaseItem, I = any, U = T
private rebuildIndicesOncePerTick = executeOncePerTick(this.rebuildAllIndices.bind(this))

private rebuildAllIndices() {
this.idIndex.clear()
// eslint-disable-next-line array-callback-return
this.memory().map((item, index) => {
this.idIndex.set(serializeValue(item.id), new Set([index]))
})
this.indexProviders.forEach(index => index.rebuild(this.memoryArray()))
this.indicesOutdated = false
}
Expand Down

0 comments on commit e8d1a33

Please sign in to comment.