Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

1.0 KB
Raw Blame
import { ScopedCache } from './ScopedCache'

const _cacheStore = new Map<string, any>()

export class MemoryCache<T extends Record<string, any>> extends ScopedCache<T> {
    private cache: Map<string, any> = new Map()

    constructor(scope: string) {
        super(scope)
        this.cache = _cacheStore.get(scope) || new Map()
        _cacheStore.set(scope, this.cache)
    }

    async get<K extends keyof T>(key: K): Promise<T[K] | undefined> {
        return this.cache.get(key as string)
    }

    async set<K extends keyof T>(key: K, value: T[K]): Promise<void> {
        this.cache.set(key as string, value)
        return
    }

    async delete<K extends keyof T>(key: K): Promise<void> {
        this.cache.delete(key as string)
    }

    async setIfAbsent<K extends keyof T>(key: K, value: T[K]): Promise<boolean> {
        if (this.cache.has(key as string)) {
            return false
        }
        this.cache.set(key as string, value)
        return true
    }

    async clear(): Promise<void> {
        this.cache.clear()
    }
}