Skip to content

Commit 7eb0985

Browse files
authored
fix: prevent clear() from skipping the delete hook (#384)
1 parent 4469113 commit 7eb0985

3 files changed

Lines changed: 47 additions & 1 deletion

File tree

‎src/collection.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,11 @@ export class Collection<Schema extends StandardSchemaV1> {
518518
* Deletes all the records in this collection.
519519
*/
520520
public clear(): void {
521-
for (const record of this.#records) {
521+
/**
522+
* @note Iterate over a copy of the records because deleting a record
523+
* removes it from the original list, which would skip every other record.
524+
*/
525+
for (const record of [...this.#records]) {
522526
this.#deleteRecord(record)
523527
}
524528

‎tests/hooks/delete.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,19 @@ it('allows preventing the default for specific records', async () => {
109109

110110
expect(users.all()).toEqual([{ id: 1 }, { id: 3 }, { id: 5 }])
111111
})
112+
113+
it('invokes the delete hook for every record when clearing the collection', async () => {
114+
const users = new Collection({
115+
schema: z.object({ id: z.number() }),
116+
})
117+
118+
const hook = vi.fn<HookEventListener<typeof users, 'delete'>>()
119+
users.hooks.on('delete', hook)
120+
121+
await users.createMany(4, (index) => ({ id: index + 1 }))
122+
123+
users.clear()
124+
125+
expect(hook).toHaveBeenCalledTimes(4)
126+
expect(users.all()).toEqual([])
127+
})

‎tests/relations/one-to-many.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,32 @@ it('cascades foreign record deletion when clearing the entire collection', async
423423
expect(users.all()).toEqual([])
424424
})
425425

426+
it('cascades foreign record deletion for every owner when clearing the entire collection', async () => {
427+
const users = new Collection({ schema: userSchema })
428+
const posts = new Collection({ schema: postSchema })
429+
430+
users.defineRelations(({ many }) => ({
431+
posts: many(posts),
432+
}))
433+
posts.defineRelations(({ one }) => ({
434+
author: one(users, { onDelete: 'cascade' }),
435+
}))
436+
437+
await users.create({
438+
id: 1,
439+
posts: [await posts.create({ title: 'First' })],
440+
})
441+
await users.create({
442+
id: 2,
443+
posts: [await posts.create({ title: 'Second' })],
444+
})
445+
446+
users.clear()
447+
448+
expect(posts.all()).toEqual([])
449+
expect(users.all()).toEqual([])
450+
})
451+
426452
it('supports unique one-to-many relations', async () => {
427453
const users = new Collection({ schema: userSchema })
428454
const posts = new Collection({ schema: postSchema })

0 commit comments

Comments
 (0)