skip to Main Content

I’m using Nest 7.1.5 and ioredis 4.17.3. I’m trying to create a RedisService and inject it afterwards.
Here is what I have so far:

redis.providers.ts

import { Provider } from '@nestjs/common';
import Redis from 'ioredis';
import { REDIS_CLIENT } from './redis.constants';

export type RedisClient = Redis.Redis;

export const redisProviders: Provider[] = [
    {
        useFactory: (): RedisClient => {
            return new Redis({
                host: 'localhost',
                port: 6379,
            });
        },
        provide: REDIS_CLIENT,
    }
]

redis.service.ts

import { Injectable, Inject } from '@nestjs/common';

import { REDIS_CLIENT } from './redis.constants';
import { RedisClient } from './redis.providers';

@Injectable()
export class RedisService {
    public constructor(
        @Inject(REDIS_CLIENT)
        private readonly redisClient: RedisClient,
    ) { }
}

redis.module.ts

import { Module } from '@nestjs/common';
import { redisProviders } from './redis.providers';
import { RedisService } from './redis.service';

@Module({
    providers: [...redisProviders, RedisService],
    exports: [...redisProviders, RedisService],
})
export class RedisModule { }

When I try to inject this service I got this error:

[12:25:57 PM] Found 0 errors. Watching for file changes.

/path/redis-setup/dist/shared/redis/redis.service.js:28
        __metadata("design:paramtypes", [typeof (_a = typeof redis_providers_1.RedisClient !== "undefined" && redis_providers_1.RedisClient) === "function" ? _a : Object])
                                                             ^

ReferenceError: redis_providers_1 is not defined
    at /path/redis-setup/dist/shared/redis/redis.service.js:28:62
    at Object.<anonymous> (/path/redis-setup/dist/shared/redis/redis.service.js:31:3)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Module.require (internal/modules/cjs/loader.js:723:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (/path/redis-setup/dist/app.service.js:14:25)
    at Module._compile (internal/modules/cjs/loader.js:816:30)

What am I missing here? Any help or thoughts are appreciated. Thank you.

2

Answers


  1. try adding "esModuleInterop": true inside your tsconfig.json

    Login or Signup to reply.
  2. You will need to install the type

    • npm install @types/ioredis --save-dev

    Then in the code you will have to change from RedisClient to simple Redis. In the latest version there’s no RedisClient as type.

    import Redis from 'ioredis';
    .....
    
    
    export type RedisClient = Redis.Redis;
    
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search