8

I was trying to connect Redis (v4.0.1) to my express server with typescript but having a bit issue. Am learning typescript. It's showing redlines on host inside redis.createClient() Can anyone help me out?

const host = process.env.REDIS_HOST;
const port = process.env.REDIS_PORT;
const redisClient = redis.createClient({
  host,
  port,
});
Argument of type '{ host: string | undefined; port: string | undefined; }' is not assignable to parameter of type 'Omit<RedisClientOptions<never, RedisScripts>, "modules">'.
  Object literal may only specify known properties, and 'host' does not exist in type 'Omit<RedisClientOptions<never, RedisScripts>, "modules">'.ts(2345)
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Robbi
  • 151
  • 2
  • 6
  • 14

4 Answers4

11

Options have changed when redis updated to 4.0.1. This should help you.

Tytrox
  • 483
  • 2
  • 10
4

This works as expected (redis v4.1.0)

const url = process.env.REDIS_URL || 'redis://localhost:6379';
const redisClient = redis.createClient({
    url
});
Archer
  • 5,073
  • 8
  • 50
  • 96
1

what I did in my project was this

file: services/internal/cache.ts

/* eslint-disable no-inline-comments */
import type { RedisClientType } from 'redis'
import { createClient } from 'redis'
import { config } from '@app/config'
import { logger } from '@app/utils/logger'

let redisClient: RedisClientType
let isReady: boolean

const cacheOptions = {
  url: config.redis.tlsFlag ? config.redis.urlTls : config.redis.url,
}

if (config.redis.tlsFlag) {
  Object.assign(cacheOptions, {
    socket: {
      // keepAlive: 300, // 5 minutes DEFAULT
      tls: false,
    },
  })
}

async function getCache(): Promise<RedisClientType> {
  if (!isReady) {
    redisClient = createClient({
      ...cacheOptions,
    })
    redisClient.on('error', err => logger.error(`Redis Error: ${err}`))
    redisClient.on('connect', () => logger.info('Redis connected'))
    redisClient.on('reconnecting', () => logger.info('Redis reconnecting'))
    redisClient.on('ready', () => {
      isReady = true
      logger.info('Redis ready!')
    })
    await redisClient.connect()
  }
  return redisClient
}

getCache().then(connection => {
  redisClient = connection
}).catch(err => {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  logger.error({ err }, 'Failed to connect to Redis')
})

export {
  getCache,
}

then you just import where you need:

import { getCache } from '@services/internal/cache'

    const cache = await getCache()
    cache.setEx(accountId, 60, JSON.stringify(account))
0

The option to add a host, port in redis.createClient is no longer supported by redis. So it is not inside type createClient. use URL instead.