Skip to content

Commit 04ac3fa

Browse files
committed
perf: cache relations for one tick
1 parent c7a8831 commit 04ac3fa

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

packages/vue/src/item.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { Collection, CollectionDefaults, ResolvedCollection, ResolvedCollec
22
import type { VueCollectionApi } from './api'
33
import type { VueStore } from './store'
44
import { peekFirst, peekMany, type UpdateOptions } from '@rstore/core'
5-
import { markRaw, type Ref } from 'vue'
5+
import { markRaw, nextTick, type Ref } from 'vue'
66

77
export interface WrapItemOptions<
88
TCollection extends Collection,
@@ -29,6 +29,8 @@ export function wrapItem<
2929
return store[collection.name as keyof typeof store] as any
3030
}
3131

32+
const relationCache = new Map<string, any>()
33+
3234
const proxy = new Proxy({}, {
3335
get: (target, key) => {
3436
switch (key) {
@@ -93,6 +95,11 @@ export function wrapItem<
9395

9496
// Resolve related items in the cache
9597
if (key in collection.relations) {
98+
const cached = relationCache.get(key as string)
99+
if (cached) {
100+
return cached
101+
}
102+
96103
if (Reflect.has(target, key)) {
97104
// @TODO resolve references
98105
return Reflect.get(target, key)
@@ -137,12 +144,20 @@ export function wrapItem<
137144
}
138145
}
139146

147+
let finalResult
140148
if (relation.many) {
141-
return result
149+
finalResult = result
142150
}
143151
else {
144-
return result[0]
152+
finalResult = result[0]
145153
}
154+
155+
relationCache.set(key as string, finalResult)
156+
nextTick(() => {
157+
relationCache.delete(key as string)
158+
})
159+
160+
return finalResult
146161
}
147162
}
148163

0 commit comments

Comments
 (0)