Eric Nishio

Simple In-Memory Cache for Node.js

Node.js
TypeScript

Here’s a simple in-memory cache that you can use in a Node.js project. No external dependencies are required.

The only thing you need to do is provide an updater function that fetches the data and a TTL value for how long you want the data to be cached.

When you call the .read() method for the first time, it fetches and caches the data and returns it.

When calling .read() on cached data, it checks if the cache is still valid and returns the cached data. If the cache is outdated, it runs the updater function and refreshes the cache before returning the data.

Implementation

ts
interface Constructor<T> {
  update: () => Promise<T>
  ttl: number
}

class MemoryCache<T> {
  private state?: T
  private ttl: number
  private lastUpdatedAt: number
  private updater: () => Promise<T>

  constructor({ update, ttl }: Constructor<T>) {
    this.ttl = ttl
    this.lastUpdatedAt = Date.now()
    this.updater = update
  }

  private isOutdated = () => {
    return Date.now() - this.lastUpdatedAt >= this.ttl
  }

  update = async () => {
    try {
      this.state = await this.updater()
      this.lastUpdatedAt = Date.now()
    } catch (e) {
      console.error('Failed to update cache:', e)
    }
  }

  read = async (): Promise<T | undefined> => {
    if (!this.state || this.isOutdated()) {
      await this.update()
    }

    return this.state
  }
}

Usage

ts
const cache = new MemoryCache<MyData>({
  ttl: 3_600_000, // 1 hour
  update: async () => fetchData(),
})

Reading the cache

ts
await cache.read()
Japanese Wax Seal: NishioCopyright 2024 Eric Nishio
XInstagramGitHubLinkedIn