Cachified - How to remove a cached value with Next.js?

168 views Asked by At

I am using cachified with lru-cache and I have an issue where I can't delete existing cache by it's key. It just doesn't show anything as if I never cached that value.

I am trying to use deleteCache('user-123') in another file, but it always returns 'false. Same with getCache('user-123'), it returns nothing.

I thought maybe this was related to lruCache creating a new instance everytime I invoke clearCache but it didn't help to only set lruCache when it is null (to prevent reassignment).

However, the console.log inside the cachedUserByName always shows the cached value, as expected.

Do you know what I am doing wrong? I am using the cachedUserByName inside getServerSideProps.

When I tried to use file-system-cache, it worked perfectly.

import { CacheEntry, cachified } from 'cachified'
import { LRUCache } from 'lru-cache'

const lruCache = new LRUCache<string, CacheEntry>({ max: 10000 })

export const cachedUserByName = (name: string): Promise<any> => {
  const cacheId = `user-${name}`
  const cacheTest = console.log(lruCache.get(cacheId));
  return cachified<any>({
    key: cacheId,
    cache: lruCache,
    async getFreshValue() {
      const { firstName, lastName } = await getInformation(name)
      return {
        information: {
          firstName,
          lastName,
        },
      }
    },
    ttl: 10 * 1000,
    staleWhileRevalidate: Infinity,
  })
}

export function getCache(key: string) {
  return lruCache.get(key)
}

export function clearCache(key: string) {
  return lruCache.delete(key)
}

In the other file, I invoke the clearCache function

import { clearCache } from '@/server/cachedApiService'
import { NextApiRequest, NextApiResponse } from 'next/types'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  console.debug('[/api/cache]', req.method)

  if (req.method === 'POST') {
    const { name } = req.body
    if (!name) {
      return res.status(400).json({
        error: 'Please provide name',
      })
    }
    const cacheToClear = `user-${name}`
    try {
      const success = clearCache(cacheToClear)
      return res.status(200).json({
        message: `${name} Cache cleared`,
        success,
      })
    } catch (e) {
      return res.status(500).json({
        message: 'Something went wrong',
      })
    }
  }
}

If you have any other memory-caching mechanism that you know, please let me know !

0

There are 0 answers