Can I nest cache functions

Can I nest cache functions and does it prevent multiple calls to the db, for instance
export const getAuthCache = cache(async () => {
'use server'

return getAuth()
}, 'getAuthCache')

export const requireAuthCache = cache(async () => {
'use server'

const auth = await getAuthCache()
if (!auth?.user) {
throw redirect('/auth/signin?error=unauthorized')
}
return auth
}, 'requireAuthCache')

export const getAccountCache = cache(async () => {
'use server'
const auth = await requireAuthCache()
return getAccountById(auth.session.selectedAccountId)
}, 'getAccountCache')
export const getAuthCache = cache(async () => {
'use server'

return getAuth()
}, 'getAuthCache')

export const requireAuthCache = cache(async () => {
'use server'

const auth = await getAuthCache()
if (!auth?.user) {
throw redirect('/auth/signin?error=unauthorized')
}
return auth
}, 'requireAuthCache')

export const getAccountCache = cache(async () => {
'use server'
const auth = await requireAuthCache()
return getAccountById(auth.session.selectedAccountId)
}, 'getAccountCache')
do i get the benefits of cache from the above code?
5 Replies
brenelz
brenelz2mo ago
I don't think nested cache functions work well. You can refactor it out
russellchoudhury
russellchoudhuryOP2mo ago
so cache is only useful when called from the frontend? What is a good way to refactor the above, auth function in particular which needs to be called in almost every server function
brenelz
brenelz2mo ago
Just use getAuth as a normal function without cache wrapper cache wrapper mainly only used with createAsync or preload
russellchoudhury
russellchoudhuryOP2mo ago
Just skimmed through the cache source code and there is a bunch of isServer logic. I would imagine from this that nested cache calls should work fine. Unless im missing something here https://github.com/solidjs/solid-router/blob/main/src/data/cache.ts
GitHub
solid-router/src/data/cache.ts at main · solidjs/solid-router
A universal router for Solid inspired by Ember and React Router - solidjs/solid-router
brenelz
brenelz2mo ago
I think it works unless you like redirect or something
Want results from more Discord servers?
Add your server