Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/visible/cruel/llms.txt

Use this file to discover all available pages before exploring further.

Function Signature

function withCache<T extends AnyFn>(
  fn: T,
  options: CacheOptions<ReturnType<T>>
): T
Wraps a function with caching. Stores results in memory with configurable time-to-live (TTL).

Options

ttl
number
required
Time-to-live in milliseconds. Cached values expire after this duration.
key
(...args: unknown[]) => string
Custom key function to generate cache keys from function arguments. Defaults to JSON.stringify(args).
onHit
(key: string) => void
Callback invoked when a cached value is found and returned.
onMiss
(key: string) => void
Callback invoked when no cached value is found and the function is executed.

Return Type

Returns the wrapped function with caching.

Types

interface CacheOptions<T> {
  ttl: number
  key?: (...args: unknown[]) => string
  onHit?: (key: string) => void
  onMiss?: (key: string) => void
}

Example

import { withCache } from 'cruel'

const cachedFetch = withCache(
  async (url: string) => {
    const response = await fetch(url)
    return response.json()
  },
  {
    ttl: 60000, // Cache for 1 minute
    key: (url) => `fetch:${url}`,
    onHit: (key) => {
      console.log(`Cache hit: ${key}`)
    },
    onMiss: (key) => {
      console.log(`Cache miss: ${key}`)
    }
  }
)

// First call - fetches from API
const data1 = await cachedFetch('https://api.example.com/data')

// Second call within TTL - returns cached value
const data2 = await cachedFetch('https://api.example.com/data')

// Call after TTL expires - fetches from API again
setTimeout(async () => {
  const data3 = await cachedFetch('https://api.example.com/data')
}, 61000)