skunight / nestjs-redis Goto Github PK
View Code? Open in Web Editor NEWnestjs redis module
License: MIT License
nestjs redis module
License: MIT License
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!
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.
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.
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) {}
}
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
[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:
`
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)
Because export interface RedisModuleOptions extends RedisOptions
, field name
is already in use by ioredis
for name of master
in SentinelConnector. You should use a different field for multi-client connection. Otherwise, it is not possible to create more than 1 client with Sentinel setup.
Hi! ๐๐ฝ
I'm trying to use the retryStrategy
property and when used with the false
value, I think it's working very well. But if I put a number I was thinking that was how many times "times" the client will try to reconnect, but for me looks like that is a way to pooling the connection until the redis-client accept connections. Am I right?
ref: https://ioredis.readthedocs.io/en/latest/README/#auto-reconnect
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)
'Nest can't resolve dependencies of the MyService (?). Please make sure that the argument at index [0] is available in the CommonModule context. '
redisService.getClients().setnx('lock', 'lock');
error: setnx is not a function
but redisService.getClients().set('lock', 'lock');
is ok
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 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
This way it's more robust, we can use our own version.
This is a best practice for these kind of libraries.
Hi, I can't find any example about how to config redis cluster. I wonder is there a plan to support redis cluster?
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
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?
Hello there!
Thanks for nice module.
I think it would be good to have healthcheck indicator for redis same as we have for typeorm
How to create a new database connection๏ผCan expose createClient()?
nestjs-redis/lib/redis-core.module.ts
Line 19 in 0715fe6
It is a packed module. But why global?
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?
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.
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
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 {
...
}
Sorry for my lack of knowledge but I need to establish the connection with my redis instance using TLS, how can I achieve that?
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?
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[]'.
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
I would like to ask how to use nestjs-redis package to achieve redis distributed lock
I'm trying to use getClient
to get the instance of RedisClient being used by nestjs-redis, but instead it's returning me an instance of IORedis.Redis, which isn't compatible with the client
parameter of connect-redis.
Looks similar to tj/connect-redis#171
how to monitoring of Redis key expired events with nestjs-redis?
Is it possible to setup connection to use master/slaves instances of Redis?
Many thanks!
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~
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 }),
`
Here's the offending line:
https://github.com/kyknow/nestjs-redis/blob/master/lib/redis-client.provider.ts#L17
If you pass in a url
, any other options are ignored:
RedisModule.register({
url: process.env.REDIS_URL,
keyPrefix: process.env.REDIS_KEY_PREFIX,
}),
What's the intended behavior here? If the URL overwrites all other options, we should document and enforce with types.
Thanks!
Anthony
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
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');
}
});
});
});
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 there any way to inject the client from contructor, intead calling getClient()
?
Somenthing like constructor(@InjectClient() redis: Redis)
.
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
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:
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.
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?
// 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.
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.
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
ไฝฟ็จ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;
}
}
I just want to know if the connection remains open after an executed command. Using redis npm package, we usually close the connection after as a good practice and to prevent consumption of resources.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.