Using withCache
const myFriends: CacheMap<{ name: string; age: number }> = {}
async function fetchMyFriendsFromCity(fromCity: string) {
// This is to preserve the name of the function in the stack trace
const fetchMyFriendsFromCity = async () => {
console.log('Fetching my friends from the database...')
return (await db.query('SELECT * FROM friends WHERE city = ?', [fromCity])).rows
}
return withCache({
cacheMap: myFriends,
cacheExpirationTimeMs: 30 * 1000, // 30 seconds cache
cacheKey: fromCity,
fetchFunctionIfCacheMiss: fetchMyFriendsFromCity,
})
console.log(await fetchMyFriendsFromCity('New York')) // Fetches from the database
console.log(await fetchMyFriendsFromCity('New York')) // Reads from the cache
await sleep(45 * 1000) // Wait for the cache to expire
console.log(await fetchMyFriendsFromCity('New York')) // Fetches from the database
Using withCacheLockable
const myFriends: CacheLockableMap<{ name: string; age: number }> = {}
async function fetchMyFriendsFromCity(fromCity: string) {
// This is to preserve the name of the function in the stack trace
const fetchMyFriendsFromCity = async () => {
console.log('Fetching my friends from the database...')
await new Promise(resolve => setTimeout(resolve, 3000)) // Simulate a slow database query
return (await db.query('SELECT * FROM friends WHERE city = ?', [fromCity])).rows
}
return withCacheLockable({
cacheMap: myFriends,
cacheExpirationTimeMs: 30 * 1000, // 30 seconds cache
cacheMaxWaitForResultIfLockedMs: 15 * 1000, // 15 seconds
cacheKey: fromCity,
fetchFunctionIfCacheMiss: fetchMyFriendsFromCity,
})
const taskA = fetchMyFriendsFromCity('New York') // Fetches from the database with lock
const taskB = fetchMyFriendsFromCity('New York') // Waiting for taskA to finish then reads from the cache
await taskA
await taskB // Will be instant because it reads from the cache
console.log(taskA)
console.log(taskB) // Same result as taskA
console.log(await fetchMyFriendsFromCity('New York')) // Data is already in cache, reads from the cache
await sleep(45 * 1000) // Wait for the cache to expire
console.log(await fetchMyFriendsFromCity('New York')) // Fetches from the database