type-cacheable icon indicating copy to clipboard operation
type-cacheable copied to clipboard

Silently ignore if connection is not available

Open stanyq4 opened this issue 2 years ago • 1 comments

I am using ioredis with type-cacheable on AWS lambdas, and from time to time, the connection to Redis will time out.

Some of my APIs are time-sensitive, and if the connection to Redis fails - I wanna skip the cache and proceed to DynamoDB as soon as possible.

Here's how Redis client configuration:

const REDIS_CONNECTION_RETRY_COUNT: number = 1;
const redisOptions: RedisOptions = {
  host: config.redis.host || 'localhost',
  port: config.redis.port || 6379,
  retryStrategy: (times): number | undefined => {
    // reconnect after
    if (times > REDIS_CONNECTION_RETRY_COUNT) {
      return undefined;
    }
    return 50;
  },
  showFriendlyErrorStack: true,
  keepAlive: 10000,
  connectTimeout: 1500,
  maxRetriesPerRequest: REDIS_CONNECTION_RETRY_COUNT,
  noDelay: true,
  lazyConnect: false,
};

As you can see, I give 1.5 seconds for connection and retry once, and if that fails - I wanna move on.

I also don't want my logs to indicate errors, so I simply log them as info

redisClient.on('error', (err) => {
  if (err?.code === 'ETIMEDOUT') {
    logger.info('Redis connection timed out, retrying...');
  } else {
    logger.error(err);
  }
  // redisClient.disconnect(false);
});

Which all works great, except, inside ioredis-adapter, if the connection is not open by the time it tries to perform get - it will throw an error

(node:2991) UnhandledPromiseRejectionWarning: Error: Connection is closed.
    at IoRedisAdapter.<anonymous> (/Users/user/Dev/projects/events-streaming/node_modules/@type-cacheable/ioredis-adapter/dist/index.js:42:51)
    at Generator.next (<anonymous>)
    at /Users/user/Dev/projects/events-streaming/node_modules/@type-cacheable/ioredis-adapter/dist/index.js:8:71

Is there a way to catch this error or tell the adapter to skip if the connection is not there?

Thank you

stanyq4 avatar Aug 31 '22 17:08 stanyq4

Hi,

I have been busy, but hope I can take a look into this soon. If you've got the time, I'd be happy to consider a PR from you for this feature.

joshuaslate avatar Sep 07 '22 22:09 joshuaslate