GithubHelp home page GithubHelp logo

nestjs-redis's Introduction

Nestjs Redis

Redis component for NestJs.

Installation

Yarn

yarn add nestjs-redis

NPM

npm install nestjs-redis --save

Getting Started

Let's register the RedisModule in app.module.ts

import { Module } from '@nestjs/common'
import { RedisModule} from 'nestjs-redis'

@Module({
    imports: [
        RedisModule.register(options)
    ],
})
export class AppModule {}

With Async

import { Module } from '@nestjs/common';
import { RedisModule} from 'nestjs-redis'

@Module({
    imports: [
        RedisModule.forRootAsync({
            useFactory: (configService: ConfigService) => configService.get('redis'),         // or use async method
            //useFactory: async (configService: ConfigService) => configService.get('redis'),
            inject:[ConfigService]
        }),
    ],
})
export class AppModule {}

And the config file look like this With single client

export default {
    host: process.env.REDIS_HOST,
    port: parseInt(process.env.REDIS_PORT),
    db: parseInt(process.env.REDIS_DB),
    password: process.env.REDIS_PASSWORD,
    keyPrefix: process.env.REDIS_PRIFIX,
}
Or
export default {
    url: 'redis://:[email protected]:6380/4',
}

With custom error handler

export default {
    url: 'redis://:[email protected]:6380/4',
    onClientReady: (client) => {
      client.on('error', (err) => {}
    )},
}

With multi client

export default [
    {
        name:'test1',
        url: 'redis://:[email protected]:6380/4',
    },
    {
        name:'test2',
        host: process.env.REDIS_HOST,
        port: parseInt(process.env.REDIS_PORT),
        db: parseInt(process.env.REDIS_DB),
        password: process.env.REDIS_PASSWORD,
        keyPrefix: process.env.REDIS_PRIFIX,
    },
]

And use in your service

import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';

@Injectable()
export class TestService {
  constructor(
    private readonly redisService: RedisService,
  ) { }
  async root(): Promise<boolean> {
    const client = await this.redisService.getClient('test')
    return true
  }
}

Options

interface RedisOptions {
    /**
     * client name. default is a uuid, unique.
     */
    name?: string;
    url?: string;
    port?: number;
    host?: string;
    /**
     * 4 (IPv4) or 6 (IPv6), Defaults to 4.
     */
    family?: number;
    /**
     * Local domain socket path. If set the port, host and family will be ignored.
     */
    path?: string;
    /**
     * TCP KeepAlive on the socket with a X ms delay before start. Set to a non-number value to disable keepAlive.
     */
    keepAlive?: number;
    connectionName?: string;
    /**
     * If set, client will send AUTH command with the value of this option when connected.
     */
    password?: string;
    /**
     * Database index to use.
     */
    db?: number;
    /**
     * When a connection is established to the Redis server, the server might still be loading
     * the database from disk. While loading, the server not respond to any commands.
     * To work around this, when this option is true, ioredis will check the status of the Redis server,
     * and when the Redis server is able to process commands, a ready event will be emitted.
     */
    enableReadyCheck?: boolean;
    keyPrefix?: string;
    /**
     * When the return value isn't a number, ioredis will stop trying to reconnect.
     * Fixed in: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/15858
     */
    retryStrategy?(times: number): number | false;
    /**
     * By default, all pending commands will be flushed with an error every
     * 20 retry attempts. That makes sure commands won't wait forever when
     * the connection is down. You can change this behavior by setting
     * `maxRetriesPerRequest`.
     *
     * Set maxRetriesPerRequest to `null` to disable this behavior, and
     * every command will wait forever until the connection is alive again
     * (which is the default behavior before ioredis v4).
     */
    maxRetriesPerRequest?: number | null;
    /**
     * 1/true means reconnect, 2 means reconnect and resend failed command. Returning false will ignore
     * the error and do nothing.
     */
    reconnectOnError?(error: Error): boolean | 1 | 2;
    /**
     * By default, if there is no active connection to the Redis server, commands are added to a queue
     * and are executed once the connection is "ready" (when enableReadyCheck is true, "ready" means
     * the Redis server has loaded the database from disk, otherwise means the connection to the Redis
     * server has been established). If this option is false, when execute the command when the connection
     * isn't ready, an error will be returned.
     */
    enableOfflineQueue?: boolean;
    /**
     * The milliseconds before a timeout occurs during the initial connection to the Redis server.
     * default: 10000.
     */
    connectTimeout?: number;
    /**
     * After reconnected, if the previous connection was in the subscriber mode, client will auto re-subscribe these channels.
     * default: true.
     */
    autoResubscribe?: boolean;
    /**
     * If true, client will resend unfulfilled commands(e.g. block commands) in the previous connection when reconnected.
     * default: true.
     */
    autoResendUnfulfilledCommands?: boolean;
    lazyConnect?: boolean;
    tls?: tls.ConnectionOptions;
    sentinels?: Array<{ host: string; port: number; }>;
    name?: string;
    /**
     * Enable READONLY mode for the connection. Only available for cluster mode.
     * default: false.
     */
    readOnly?: boolean;
    /**
     * If you are using the hiredis parser, it's highly recommended to enable this option.
     * Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string
     */
    dropBufferSupport?: boolean;
    /**
     * Whether to show a friendly error stack. Will decrease the performance significantly.
     */
    showFriendlyErrorStack?: boolean;
}

That's it!

nestjs-redis's People

Contributors

dependabot[bot] avatar gyanendrokh avatar hkjeffchan avatar iamolegga avatar mentatxx avatar notiv-nt avatar rifatdover avatar sashkopavlenko avatar skunight avatar teralad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nestjs-redis's Issues

default client is exists Error: default client is exists

Hi,would you consider supporting the cluster? IORedis.Cluster. thanks.

RedisModule.forRootAsync({
    useFactory: (config: Boot) => {
        return [
            {
                host: '192.168.1.84',
                port: '6379',
                db: 0,
                password: 'xxx',
            },
            {/** more */},
            /** more */
        ]
    }
})

ERROR:

default client is exists Error: default client is exists
    at InstanceWrapper.useFactory [as metatype] (/Users/micro-application/node_modules/nestjs-redis/dist/redis-client.provider.js:29:31)
    at Injector.instantiateClass (/Users/micro-application/node_modules/@nestjs/core/injector/injector.js:291:55)
    at callback (/Users/micro-application/node_modules/@nestjs/core/injector/injector.js:75:41)
    at async Injector.resolveConstructorParams (/Users/micro-application/node_modules/@nestjs/core/injector/injector.js:116:24)
    at async Injector.loadInstance (/Users/micro-application/node_modules/@nestjs/core/injector/injector.js:79:9)
    at async Injector.loadProvider (/Users/micro-application/node_modules/@nestjs/core/injector/injector.js:36:9)
    at async Promise.all (index 4)
    at async InstanceLoader.createInstancesOfProviders (/Users/micro-application/node_modules/@nestjs/core/injector/instance-loader.js:41:9)
    at async /Users/micro-application/node_modules/@nestjs/core/injector/instance-loader.js:27:13
    at async Promise.all (index 15)
    at async InstanceLoader.createInstances (/Users/micro-application/node_modules/@nestjs/core/injector/instance-loader.js:26:9)
    at async InstanceLoader.createInstancesOfDependencies (/Users/micro-application/node_modules/@nestjs/core/injector/instance-loader.js:16:9)
    at async /Users/micro-application/node_modules/@nestjs/core/nest-factory.js:82:17
    at async Function.asyncRun (/Users/micro-application/node_modules/@nestjs/core/errors/exceptions-zone.js:17:13)
    at async NestFactoryStatic.initialize (/Users/micro-application/node_modules/@nestjs/core/nest-factory.js:80:13)
    at async NestFactoryStatic.create (/Users/micro-application/node_modules/@nestjs/core/nest-factory.js:31:9)

so, add the name field

{
    name: 'some name'
    host: '192.168.1.84',
    port: 6379,
    db: 0,
    password: 'xxx',
}

ERROR:

(error) MOVED 12539 192.168.1.85:6379

A distributed lock

I would like to ask how to use nestjs-redis package to achieve redis distributed lock

Publish the last changes to npm

Hi, @skunight
Could you please publish the last version of your package into the public NPM registry?

Would be great to use the last adaptation for nestjs@8.*

Thank you in advance

Nest8 + redis still not working with npm

Hello,

While working with nestjs-redis package I am getting the following error:

Nest can't resolve dependencies of the RedisCoreModule (Symbol(REDIS_MODULE_OPTIONS), ?). Please make sure that the argument ModuleRef at index [1] is available in the RedisCoreModule context

The issue was supposedly resolved in this issue https://github.com/skunight/nestjs-redis/issues/82,
but the changes were never rolled out when working with npm.

Using:
"@nestjs/common": "^8.1.1",
"@nestjs/core": "^8.1.1",

only workaround in the moment is either moving the package into the project, or using a different nestjs-redis source, like so:
"nestjs-redis": "git+https://github.com/skunight/nestjs-redis.git",

I am sure I am not the only one with this issue

Is there a way to get ioredis instance from nestjs-redis?

I'm using this Nestjs Redis component and I saw that component is using ioredis. What happens is that I want to save geoinformation through GEOADD command available on Redis and available also in the ioredis.

So, how can I get an ioredis instance from a Nestjs-Redis instance? Is it possible?

Thanks in advance!

Nest 8 + redis bug

[Nest] 2697522 - 07/09/2021, 12:43:37 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the RedisCoreModule (Symbol(REDIS_MODULE_OPTIONS), ?). Please make sure that the argument ModuleRef at index [1] is available in the RedisCoreModule context.

Potential solutions:

  • If ModuleRef is a provider, is it part of the current RedisCoreModule?
  • If ModuleRef is exported from a separate @module, is that module imported within RedisCoreModule?
    @module({
    imports: [ /* the Module containing ModuleRef */ ]
    })

Jest encountered an unexpected token

After running tests with the default nestjs jest configuration, I get the error:

  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /home/a/reflect/app/node_modules/nestjs-redis/index.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './dist'
                                                                                             ^^^^^^

    SyntaxError: Unexpected token export

      3 | import { getRepositoryToken } from '@nestjs/typeorm';
    > 4 | import { RedisModule } from 'nestjs-redis';

Looks like the issue is caused by index.ts file that is present in the root folder of the package. Is there any reason why it's included?

is not assignable to parameter of type 'RedisModuleOptions | RedisModuleOptions[]'.

Thanks for your work first of all.

When I add config, got error below:

Error:(22, 7) TS2345: Argument of type '{ name: string; host: string; port: number; db: number; password: string; keyPrefix: string; }' is not assignable to parameter of type 'RedisModuleOptions | RedisModuleOptions[]'.
Object literal may only specify known properties, and 'host' does not exist in type 'RedisModuleOptions | RedisModuleOptions[]'.

image

Is look like lack of definition, is only name defined
image

Documentation for Tests

Hi is there any available example on how to mock the RedisModule for unit test scenarios?

I tried to setup a CacheModule as follows:

@Module({
  imports: [
    RedisModule.forRootAsync({
      useFactory: (configService: ConfigService) => configService.redisConfig(),
      inject: [ConfigService],
    }),
  ],
  providers: [CacheService],
  exports: [CacheService],
})
export class CacheModule {}

However running unit tests I get the following issue:

  Nest can't resolve dependencies of the CACHE_MANAGER (?). Please make sure that the argument at index [0] is available in the CacheModule context.

      at Injector.lookupComponentInExports (node_modules/@nestjs/core/injector/injector.js:144:19)

I know this is something that I can probably workaround, but I guess it would be a good idea to document the best approach to create a module that handles Nest Test correctly.

Some vulnerabilities require your attention to resolve. [High : Server-Side Request Forgery]

───────────────┬──────────────────────────────────────────────────────────────┐
│ High │ Server-Side Request Forgery │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ axios │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in │ >=0.21.1 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ nestjs-redis │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ nestjs-redis > @nestjs/common > axios │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://npmjs.com/advisories/1594

TS2345: Argument of type '{ imports: DynamicModule[]; exports: (typeof ConfigService)[];

TS2345: Argument of type '{ imports: DynamicModule[]; exports: (typeof ConfigService)[]; controllers: (typeof ConfigControl...' is not assignable to parameter of type 'ModuleMetadata'.
Types of property 'imports' are incompatible.
Type 'DynamicModule[]' is not assignable to type '(Type | DynamicModule | Promise | ForwardReference)[]'.
Type 'DynamicModule' is not assignable to type 'Type | DynamicModule | Promise | ForwardReference'.
Type 'DynamicModule' is not assignable to type 'ForwardReference'.
Property 'forwardRef' is missing in type 'DynamicModule'.

13 @module({
~
14 imports: [

my code:
@global()
@module({
imports: [
RedisModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.getRedisConfig(),
inject: [ConfigService]
})
],
exports: [ConfigService],
controllers: [ConfigController],
providers: [
ConfigService,
{
provide: DefaultConfig,
useValue: new DefaultConfig(), // 默认只使用值
},
],
})
export class ConfigModule {
...
}

(feature request) Redis Interceptor

Hey! Thanks for all the hard work you've made on this package!

I used this package in a code test recently and I built a redis interceptor for caching my routes responses.

It might be handy for others to use this interceptor so I was going to ask, would you like me to add a PR to add the interceptor?

I used it like this

@Controller()
export class TestController {

  constructor (private readonly api: SomeApiClientOrWhatever) {}

  @Get('some/path')
  @UseInterceptor(RedisInterceptor)
  async cacheMe(@Query('page') page: number = 1, @Query('limit') limit: number = 10): Promise<SomeObject[]> {
     return await this.api.get(`get/loads/of/things?page=${page}&per_page=${limit}`);
  }
}

The above would cache the response of cacheMe using the request url + method as the key like so GET.some/path?page=1&limit=10 or GET.some/path. When the cache key exists on a second request, the cache is used rather than calling the method a second time

Inject client from constructor

Is there any way to inject the client from contructor, intead calling getClient()?

Somenthing like constructor(@InjectClient() redis: Redis).

Dynamic Module Typescript Error

I tried to get this up and running based on the readme, but I keep getting an error on npm start:

My App Module:

`
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { SharedModule } from './shared/shared.module';
import { ApiModule } from './api/api.module';
import { ConfigModule } from './config/config.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { RedisModule } from 'nestjs-redis';

@module({
imports: [
SharedModule,
ApiModule,
ConfigModule,
TypeOrmModule.forRoot({
type: 'mongodb',
host: 'localhost',
port: 27017,
database: 'test',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
RedisModule.register({
host: 'localhost',
port: 6379,
db: 1,
password: '',
keyPrefix: '_backend',
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

`

On NPM start, the error I see:

`
/Users/tskweres/dev/backend-starter/node_modules/ts-node/src/index.ts:240
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
src/app.module.ts:23:5 - error TS2322: Type 'DynamicModule' is not assignable to type 'Type | DynamicModule | Promise | ForwardReference'.
Type 'import("/Users/tskweres/dev/backend-starter/node_modules/nestjs-redis/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface").DynamicModule' is not assignable to type 'import("/Users/tskweres/dev/backend-starter/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface").DynamicModule'.
Types of property 'imports' are incompatible.
Type '(DynamicModule | Type | Promise | ForwardReference)[]' is not assignable to type '(Type | DynamicModule | Promise | ForwardReference)[]'.
Type 'DynamicModule | Type | Promise | ForwardReference' is not assignable to type 'Type | DynamicModule | Promise | ForwardReference'.
Type 'DynamicModule' is not assignable to type 'Type | DynamicModule | Promise | ForwardReference'.

23 RedisModule.register({
~~~~~~~~~~~~~~~~~~~~~~
24 host: 'localhost',
~~~~~~~~~~~~~~~~~~~~~~~~
...
28 keyPrefix: '_backend',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
29 }),
`

In Jest UT, Nest can't resolve dependencies of the RedisService (?). Please make sure that the argument Symbol(REDIS_CLIENT) at index [0] is available in the RootTestModule context.

I have written the simple UT in Jest and also used nestjs-redis module for redis operation when i run the UT i am getting following error, i tried to mock as fn() but getting same issue.

Nest can't resolve dependencies of the RedisService (?). Please make sure that the argument Symbol(REDIS_CLIENT) at index [0] is available in the RootTestModule context.

   Potential solutions:
   - If Symbol(REDIS_CLIENT) is a provider, is it part of the current RootTestModule?
   - If Symbol(REDIS_CLIENT) is exported from a separate @Module, is that module imported within RootTestModule?
     @Module({
       imports: [ /* the Module containing Symbol(REDIS_CLIENT) */ ]
     })

Below is the code

import { Test, TestingModule } from '@nestjs/testing';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
import { getModelToken } from '@nestjs/mongoose';
import { RedisService } from '../../shared/lib/redis/redis.service';
describe('CatsController', () => {
    let controller: CatsController;
    let service: CatsService;
    
  beforeEach(async () => {
    const app: TestingModule = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [CatsService, RedisService, { provide: getModelToken('Cats'), useValue: { Symbol: jest.fn()} }],
    }).compile();

    controller = app.get<CatsController>(CatsController);
    service = app.get<CatsService>(CatsService);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
    expect(service).toBeDefined();
  });

  const catsData = [{
      cat_name: "cat",
      cat_type: "type",
      cat_color: "black"
  }]
  describe('Cats List', () => {


    it('should return all cats', async() => {
        jest.spyOn(service, 'getAll').mockResolvedValue({data: catsData, success: true})
        const catsList = await controller.findAll()
      expect(catsList).toBe({data: catsData, success: true});
    });

    it('should throw error record not found', async() => {
        jest.spyOn(service, 'getAll').mockRejectedValue({message: 'Records not found'})
        try{
            await controller.findAll();
          }catch(e){
            expect(e.message).toBe('Records not found');
          }
      });

  });
});

Create a proper example with README how to add Redis module and consume it in application to listen to Redis client !!

Please
Create a proper example with README how to add Redis module and consume it in application to listen to Redis client !!

import { DynamicModule } from '@nestjs/common';
import { RedisModule, RedisModuleOptions} from 'nestjs-redis';
import { RedisConfigError } from '../database/db.error';
import { ConfigModule } from '../config/config.module';
import { ConfigService } from '../config/config.service';
export class CacheModule {
  public static getRedisOptions(config: ConfigService): RedisModuleOptions {
    const redisConfig = config.get().redis;
    if (!redisConfig) {
      throw new RedisConfigError('redis config is missing');
    }
    return redisConfig as RedisModuleOptions;
  }

  public static forRoot(): DynamicModule {
    return {
      module: CacheModule,
      imports: [
        RedisModule.forRootAsync({
          imports: [ConfigModule],
          useFactory: (configService: ConfigService) => CacheModule.getRedisOptions(configService),
          inject: [ConfigService]
      }),

      ],
      controllers: [],
      providers: [],
      exports: [],
    };
  }
}

Look like some dependancy is breaking when i am trying to create service and injecting that service in controllers where i have already added this redisModule in main module

Nest can't resolve dependencies of the RedisCoreModule (Symbol(REDIS_MODULE_OPTIONS), ?). Please make sure that the argument ModuleRef at index [1] is available in the RedisCoreModule context.

// config.ts
export const redisConfig: RedisModuleOptions = {
  url: 'redis://treehole:redis@localhost:6379/1',
}
import databaseConfig, { redisConfig } from './config/database.config'

@Module({
  imports: [TypeOrmModule.forRoot(databaseConfig), UserModule, AuthModule, RedisModule.register(redisConfig)],
  controllers: [],
  providers: [],
})
export class AppModule {}

But it gave me an error

[Nest] 35656  - 2022/02/14 下午3:50:35   ERROR [ExceptionHandler] Nest can't resolve dependencies of the RedisCoreModule (Symbol(REDIS_MODULE_OPTIONS), ?). Please make sure that the argument ModuleRef at index [1] is available in the RedisCoreModule co
ntext.

Potential solutions:
- If ModuleRef is a provider, is it part of the current RedisCoreModule?
- If ModuleRef is exported from a separate @Module, is that module imported within RedisCoreModule?
  @Module({
    imports: [ /* the Module containing ModuleRef */ ]
  })

Error: Nest can't resolve dependencies of the RedisCoreModule (Symbol(REDIS_MODULE_OPTIONS), ?). Please make sure that the argument ModuleRef at index [1] is available in the RedisCoreModule context.

Potential solutions:
- If ModuleRef is a provider, is it part of the current RedisCoreModule?
- If ModuleRef is exported from a separate @Module, is that module imported within RedisCoreModule?
  @Module({
    imports: [ /* the Module containing ModuleRef */ ]
  })

    at Injector.lookupComponentInParentModules (C:\Dev\hfut-tree-hole\nest\node_modules\@nestjs\core\injector\injector.js:202:19)
    at Injector.resolveComponentInstance (C:\Dev\hfut-tree-hole\nest\node_modules\@nestjs\core\injector\injector.js:157:33)

What happen? And what should i do to solve it? I'm sure that the redis server is no wrong.

Is getClient() stateless?

When using the default client, is the getClient() function stateless or is a NodeJS application running in a different thread not able to get the matching client? It is generating a unique ID for the client name if non is initialized. How is this handled when clustering the NodeJS application with e.g. pm2?

Is this in active development?

The common dependency is very out to date at this point, and needs to be updated. Also there is a bug where the RedisService is not registering in 6.3.1

nestjs can't resolve RedisService dependency if not in root module

Hi,
I'm registering RedisModule in my app module and in another module I have a provider that has the RedisService as dependency.

When I start the server, I get an error message:

Error: Nest can't resolve dependencies of the MyService (?). Please make sure that the argument at index [0] is available in the OtherModule context.

Looks like nestjs can't find the RedisService provider.

Here is the code:
app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { OtherModule } from './other/other.module';
import { RedisModule } from 'nestjs-redis';

@Module({
  imports: [RedisModule.register({ host: 'localhost' }), OtherModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

And in other.module.ts:

import { Module } from '@nestjs/common';
import { MyService } from './my/my.service';

@Module({
  providers: [MyService]
})
export class OtherModule {}

And in my-service.ts:

import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';

@Injectable()
export class MyService {
  constructor(redisService: RedisService) {}
}

Is this library abandoned?

This is popular library, but I see, that some of PRs are not merged, but seems to be ready (one of them is mine). Also I think that I could invest my time in covering this lib with tests, but I'm not sure if it has any sense if it will not be merged

Move deps to peer deps

Hi, thanks for package!

I see, that there are packages, that could be moved to peer dependencies, because every nest app already use it:

"@nestjs/common": "6.3.1",
"reflect-metadata": "^0.1.12",
"rxjs": "^6.2.2",

Would you mind if I'll create PR to fix this?

DynamicModule is not assignable to type

`
import { RedisModule } from 'nestjs-redis';

@module({
imports: [
RedisModule.register({
name: '',
host: '',
port: 6379,
db: 1,
password: '',
keyPrefix: '_dream'
}),
})

return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
src/app.module.ts(33,5): error TS2322: Type 'DynamicModule' is not assignable to type 'Type | DynamicModule | Promise | ForwardReference'.
Type 'import("E:/serve/node_modules/nestjs-redis/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface").DynamicModule' is not assignable to type 'import("E:/serve/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface").DynamicModule'.
Types of property 'imports' are incompatible.
Type '(DynamicModule | Type | Promise | ForwardReference)[]' is not assignable to type '(Type | DynamicModule | Promise | ForwardReference)[]'.
Type 'DynamicModule | Type | Promise | ForwardReference' is not assignable to type 'Type | DynamicModule | Promise | ForwardReference'.
Type 'DynamicModule' is not assignable to type 'Type | DynamicModule | Promise | ForwardReference'.

at createTSError (E:\serve\node_modules\ts-node\src\index.ts:261:12)
at getOutput (E:\serve\node_modules\ts-node\src\index.ts:367:40)
at Object.compile (E:\serve\node_modules\ts-node\src\index.ts:558:11)
at Module.m._compile (E:\serve\node_modules\ts-node\src\index.ts:439:43)
at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Object.require.extensions.(anonymous function) [as .ts] (E:\serve\node_modules\ts-node\src\index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)

I use yarn to instead of npm but the error still
yarn add nestjs-redis -S
(https://github.com/kyknow/nestjs-redis/issues/11)

throw exceptions if redis not exists

hello, first of all: nice module. Thank you for that.

To my problem:
I would use this redis connection not as requirement. That means: If no env variables for redis exists, the redis doesen´t connect to any host. But at the moment the module sad, that connection timeout for 127.0.0.1.

Is it possible to disable this warning?

My code:

import { Module } from '@nestjs/common';
import { RedisModule as NestJsRedisModule } from 'nestjs-redis';

@Module({
  imports: [
    NestJsRedisModule.forRootAsync({
      useFactory: () => {
        if (process.env.REDIS_HOST) {
          return {
            host: process.env.REDIS_HOST
          };
        }

        return {};
      },
    }),
  ],
})
export class RedisModule {}

Thank you very much.

RedisModule makes Jest testing hang

Description

Nest.js project by default comes with a nice integration with Jest testing framework. Injecting RedisModule into testing module causes tests command to hang after execution and not exit properly.

I already experienced such problems with testing frameworks connecting to databases. It might be resolved by somehow disconnecting from Redis once all tests have passed. The docs do not say how to disconnect.

Reasons to import it into tests:

  • I may create integration tests that actually use Redis
  • I may create a client to only mock its methods after that
  • I have many tests that just import the entire AppModule as is along with RedisModule. Then I test services that may not even actually use the module.

Versions

  • nestjs: 6.11.7
  • jest: 24.9.0
  • nestjs-redis: 1.2.5

Steps to reproduce

Use nest new command from @nestjs/cli to create project. At this point npm run test correctlly exits after execution. Now install nestjs-redis and inject it inside testing module.

That's app.controller.spec.ts file

const app: TestingModule = await Test.createTestingModule({
  imports: [
    RedisModule.register({
      host: 'localhost',
      port: 6379,
    })
  ],
  controllers: [AppController],
  providers: [AppService],
}).compile();

Now run npm run test. The test is green but it does not exit, the command hangs with this output:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.
detectOpenHandles flag does not help.

setnx is not a function

redisService.getClients().setnx('lock', 'lock');

error: setnx is not a function

but redisService.getClients().set('lock', 'lock'); is ok

Nest can't resolve dependencies of the RedisService - Symbol(REDIS_CLIENT)

Hi! Can anyone help me?

On Application start i got this error:

Nest can't resolve dependencies of the RedisService (?). Please make sure that the argument Symbol(REDIS_CLIENT) at index [0] is available in the RedisModule context.

my source

config

import { RedisModuleOptions } from 'nestjs-redis';

export const redis: RedisModuleOptions = {
  name: 'redis',
  host: process.env.REDIS_HOST,
  port: parseInt(process.env.REDIS_PORT),
  db: parseInt(process.env.REDIS_DB),
  password: process.env.REDIS_PASSWORD,
};

module

import { Module } from '@nestjs/common';
import { RedisModule, RedisService } from 'nestjs-redis';
import { MyRedisService } from './redis.service';

import { redis } from './redis.config';
@Module({
  imports: [RedisModule.register(redis)],
  providers: [MyRedisService, RedisService],
  exports: [MyRedisService],
})
export class MyRedisModule {}

service

mport { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';

@Injectable()
export class MyRedisService {
  constructor(private readonly _redisService: RedisService) {}
}

Demo or example

Is there a demo or example on how I can use this in my project? What is ConfigService? What are the dependencies? Should I have 'ioredis' already installed?

RedisModule.register does not accept URL

luin/ioredis accepts a URL string parameter, but RedisModule does not. This makes deployment to services like Heroku which provide and auto rotate a URL instead of individual connection parameters difficult.

RangeError: Maximum call stack size exceeded with jest

Hi, guys. I have some problem with jest test. If provider inject the redisService, then run test will crash RangeError: Maximum call stack size exceeded.

import { Module, Provider } from '@nestjs/common'
import { RedisModule } from 'nestjs-redis'
import { RedisNames } from './redis/redis.types'

@Module({
  imports: [
    RedisModule.register([
      {
        name: RedisNames.Access,
        keyPrefix: 'mx_access_',
      },
      {
        name: RedisNames.Like,
        keyPrefix: 'mx_like_',
      },
      {
        name: RedisNames.LoginRecord,
        keyPrefix: 'mx_' + RedisNames.LoginRecord + '_',
      },
    ]),
  ],
})
export class CommonModule {}

posts.service injected redis service.

FAIL  src/shared/posts/posts.service.spec.ts
  ● Test suite failed to run

    RangeError: Maximum call stack size exceeded

      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:52:26)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)
      at Object.genDebugFunction [as default] (node_modules/ioredis/built/utils/debug.js:53:31)

how to get bitmap

使用redis做签到数据
/*
*redis
*setbit a 11 1
*使用下面的方法直接get key
*控制台返回 'value:: '
*直接返回数据,swagger里面显示返回的是一个特殊字符
*请教一下如何获取二进制的bitmap数据,不然获取签到数据要循环很多次肯定是不科学的
*/
public async getBitValue(key: string): Promise {
if (!this.client) {
await this.getClient();
}
const data = await this.client.get(key);
if (data) {
console.log('value:: ' + data);
return data;
} else {
return null;
}
}

how to use in guard

hi
thank you

but i have a problem

in service ,it is ok

but how to use it in guard

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { ApiException } from '../filters/api.exception';
import { ApiCode } from '../enums/api-code.enums';
import { RedisService } from 'nestjs-redis';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly redisService: RedisService) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const ctx = context.switchToHttp();
    const request = ctx.getRequest();
    const url = request.originalUrl;
    if (url === '/user-info2') {
      return true;
    } else {
      //  redis中检查token
      throw new ApiException('非法登录状态', ApiCode.TOKEN_ERROR, 200);
    }
  }
}

problem:
An argument for 'redisService' was not provided

how can i use it?

thank you~

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.