17

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)

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

Comments

5

This works as expected (redis v4.1.0)

const url = process.env.REDIS_URL || 'redis://localhost:6379';
const redisClient = redis.createClient({
    url
});

Comments

5

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))

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.