This example shows a simple cache using JavaScript Map. It stores user data for 30 seconds to avoid repeated database calls.
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'https://xyzcompany.supabase.co'
const supabaseKey = 'public-anonymous-key'
const supabase = createClient(supabaseUrl, supabaseKey)
// Simple cache object
const cache = new Map()
// Function to set cache with TTL
function cacheSet(key, value, ttl) {
cache.set(key, { value, expires: Date.now() + ttl * 1000 })
}
// Function to get cache
function cacheGet(key) {
const cached = cache.get(key)
if (!cached) return null
if (Date.now() > cached.expires) {
cache.delete(key)
return null
}
return cached.value
}
async function getUser(userId) {
const cachedUser = cacheGet(userId)
if (cachedUser) {
console.log('Returning cached user')
return cachedUser
}
const { data, error } = await supabase
.from('users')
.select('*')
.eq('id', userId)
.single()
if (error) {
console.error('Error fetching user:', error)
return null
}
cacheSet(userId, data, 30) // Cache for 30 seconds
console.log('Returning fresh user')
return data
}
// Example usage
(async () => {
const user1 = await getUser('123')
console.log(user1)
const user2 = await getUser('123')
console.log(user2)
})()