DEV Community

Cover image for Simple Cache with Redis
Sibelius Seraphini for Woovi

Posted on

Simple Cache with Redis

After writing about all the use cases of Redis at Woovi, the idea is to deep dive into how to implement each of these use cases.

You can read the other use cases here Redis at Woovi

Redis Cache in Node

You just need to learn about 2 Redis commands setex and get

setex
get

The implementation is pretty straightforward:

const redis = new Redis(config.REDIS_HOST);

export const redisCacheSetex = (key: RedisKey, seconds: number, value: string) 
=> return redis.setex(key, seconds, value);

export const redisCacheGet = (key: RedisKey): Promise<string> 
=> return redis.get(key)
Enter fullscreen mode Exit fullscreen mode

If you always want to use objects instead of strings, you could have:

const redis = new Redis(config.REDIS_HOST);

export const redisCacheSetex = (key: RedisKey, seconds: number, value: Record<string, unknown>) 
=> return redis.setex(key, seconds, JSON.stringify(value));

export const redisCacheGet = async <T extends Record<string, unknown>>(
  key: RedisKey,
): Promise<T | null> => {
  const value = await redis.get(key);

  if (!value) {
    return value;
  }

  try {
    return JSON.parse(value);
  } catch (err) {
    return value;
  }
};
Enter fullscreen mode Exit fullscreen mode

Caching OAuth2 tokens

export const apiOAuth2 = async () => {
  const cacheKey = 'apiOAuth2';

  const cached = await redisCacheGet(cacheKey);

  if (cached) {
    return cached;
  }

  const response = await fetch(url, options);
  const data = await response.json();

  if (data.access_token && data.token_type && data.expires_in) {
    // remove 30 seconds from expires_in
    const ttl = data.expires_in - OAUTHTOKEN_TTL_GAP;

    if (ttl > 0) {
      // cache key
      await redisCacheSetex(cacheKey, ttl, data);
    }
  }

  return data;
};
Enter fullscreen mode Exit fullscreen mode

You can easily cache any API, GraphQL resolver, or database query.

In Conclusion

Adding a cache with Redis is pretty simple.
If you are suffering with some slow external APIs, or slow database queries that won't change the result often, a cache can help you.
Prefer to optimize APIs, and database queries over an external cache, make things faster and light so you don't need to cache.


Woovi is an innovative startup revolutionizing the payment landscape. With Woovi, shoppers can enjoy the freedom to pay however they prefer. Our cutting-edge platform provides instant payment solutions, empowering merchants to accept orders and enhance their customer experience seamlessly.

If you're interested in joining our team, we're hiring! Check out our job openings at Woovi Careers.

Top comments (1)

Collapse
 
andersonlimahw profile image
Anderson Lima

Nice!