liaoliaots / nestjs-redis Goto Github PK
View Code? Open in Web Editor NEWRedis(ioredis) module for Nest framework (node.js).
Home Page: https://npmjs.com/package/@liaoliaots/nestjs-redis
License: MIT License
Redis(ioredis) module for Nest framework (node.js).
Home Page: https://npmjs.com/package/@liaoliaots/nestjs-redis
License: MIT License
As I have changed from https://github.com/skunight/nestjs-redis to your nestjs-client(because your package is a lot better maintained), my core service is not able to connect to redis and throws all the time this error:
Even though the redis config seems to be okay (e2e testing with a redis-testcontainer is working), the microservice is not starting.
I also tried to hardcode the URL, in the case that the envs are not the right one.
My docker-compose redis config:
Is there anything wrong in the config or am I missing something?
Thanks a lot in advance !
For the module to work with Nestjs V9
When installing the package it was unable to resolve the dependency tree
peer @nestjs/common@"^8.0.0 || ^7.0.0" from @liaoliaots/[email protected]
npm i @liaoliaots/nestjs-redis
Trying to use the package with Nestjs app V9
Any ETA on ability to select database? Was looking into this package but had to drop it because of that.
Thanks.
I'm not sure if this is expected behavior but I figured out the usages of InjectRedis
needs to be prior to the RedisModule.forRoot,
otherwise, it throws an unresolved dependency error.
Digging into the code, it seems createRedisClientProviders relies on the namespaces
,
while the namespaces only got set within InjectRedis decorator
That means it doesn't work if I want to use a lazy-inject
with decorators after the RedisModule's initialization(forRoot).
I submitted a branch here: https://github.com/xavierchow/nestjs-redis/tree/dependency-issue/sample/01-testing-inject to reproduce the issue. (you can try to npm run the 01-testing-inject
sample project)
Instead of the namespaces
set by the decorators, we can use the options.config.namespace
to create providers in the createRedisClientProvider function.
@liaoliaots does it sound good to you? I'm ok with sending a PR if needed.
Your issue may already be reported!
Please search on the issue tracker before creating one.
No Type errors
Using an ioredis
5.3.1 client causes a type error
Update ioredis
dependency. This may break < 5.3.1 compatibility?
ioredis
5.3.1RedisPubSub
using ioredis
clientIn separate project everything works fine, but in yarn workspaces all projects with RedisModule gives error
RedisModule should be initialized
Error: Nest can't resolve dependencies of the RedisModule (?). Please make sure that the argument ModuleRef at index [0] is available in the RedisModule con
text.
Potential solutions:
Here is my AppModule imports:
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
RMQModule.forRootAsync(getRMQConfig()),
RedisModule.forRootAsync(getRedisConfig()),
...
]
// --- getRedisConfig
export const getRedisConfig = (): RedisModuleAsyncOptions => ({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
config: {
host: configService.getOrThrow('SHARED_REDIS_HOST'),
port: Number(configService.getOrThrow('SHARED_REDIS_PORT')),
password: configService.getOrThrow('SHARED_REDIS_PASSWORD'),
db: Number(configService.getOrThrow('SHARED_REDIS_MAIN_DB')),
},
}),
});
Nestjs microservice just supports the node-redis and there is no strategy for the ioredis.
No response
No response
Develop an ioredis' strategy connector for the Nestjs microservice.
I want to use it with the custom decorator, but the error undefin is reported here.
[stackoverflow](https://stackoverflow.com/questions/52106406/in-nest-js-how-to-get-a-service-instance-inside-a-decorator)No response
No response
No response
"@liaoliaots/nestjs-redis": "^8.0.0",
16.4
No response
Hello,liaoliao, I quoted your dependency in the project.
I have encountered a problem and would like to ask you.
in app.module.ts
@Module({
imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
RedisModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('dbConfig').redis,
inject: [ConfigService],
}),
],
})
in redis.service.ts
import { Injectable } from '@nestjs/common'
import { RedisService } from '@liaoliaots/nestjs-redis'
import Redis from 'ioredis';
@Injectable()
export class redisServiceCustom {
// Redis ===> Cannot use namespace 'Redis' as a type.
private readonly redis: Redis;
constructor(private readonly redisService: RedisService) {
this.redis = this.redisService.getClient();
}
}
at this time, the terminal throws an error
Redis client "default" was not found in the application context.
@nestjs/terminus a good practice to monitor app availability. And is a must have the second you deploy to K8s. But you should not enforce this on users of this library.
As is @nestjs/terminus must be installed in order for this library to work. This should be easily decoupled.
Module file:
import { Module, Global } from '@nestjs/common';
import { RedisModule } from '@liaoliaots/nestjs-redis';
import { ConfigService } from '@nestjs/config';
import { RedisConfig } from '../../config/config.interface';
import { ConfigKey } from '../../common/enum';
const modules = [
RedisModule.forRootAsync({
inject: [ConfigService],
useFactory: async (config: ConfigService) => {
const redisConfig = config.get(ConfigKey.LOGIN_REDIS);
console.log(redisConfig);
return {
readyLog: true,
errorLog: true,
config: {
host: 'xxxxxxxx',
port: xxx,
password: 'xxxx',
},
};
},
}),
];
@global()
@module({
imports: modules,
exports: modules,
})
export class RedisConnectionModule {}
Service File:
import { Injectable } from '@nestjs/common';
import { RedisService as RedisInternalService, DEFAULT_REDIS_NAMESPACE } from '@liaoliaots/nestjs-redis';
import Redis from 'ioredis';
@Injectable()
export class RedisService {
private readonly cacheManager: Redis;
constructor(private readonly redisService: RedisInternalService) {
this.cacheManager = this.redisService.getClient(DEFAULT_REDIS_NAMESPACE);
}
// Currently creating a custom function but will replace once increment function available with mem cache
async incrementValue(key, expiry: number = 30 * 60): Promise {
const currentValue: string = await this.cacheManager.get(key);
const safeIntValue = currentValue === null ? 0 : parseInt(currentValue, 10);
await this.cacheManager.set(key, safeIntValue + 1, 'EX', expiry);
// await this.cacheManager.set('key', 'value', 'EX', expiry);
return safeIntValue + 1;
}
async setLoginToken(
token: string,
value,
expiry = 30 * 60 * 60 * 24,
): Promise {
return this.cacheManager.set(token, value, 'EX', expiry);
}
async getLoginToken(token: string): Promise {
return this.cacheManager.get(token);
}
}
Dependencies:
"@liaoliaots/nestjs-redis": "^9.0.5",
"ioredis": "^5.2.4",
"@nestjs/apollo": "^10.1.4",
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/graphql": "^10.1.5",
Redis server is AWS cluster and i am pointing to master node.
**Request goes to infinte loading.
Note: With simple redis setup with redis version 3.1.2 , things working fine.
Stuck with these problem from last few days. Need help on priority**
As mentioned in the title, I set readyLog: true
and found that it just keep logging default: Connected successfully to server
.
Is this a feature ? Or maybe I made a mistake somewhere?
[Nest] 35946 - 2022/05/08 06:00:28 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:31 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:35 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:38 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:41 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:44 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:48 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:51 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:54 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:00:57 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:01:00 LOG [RedisModule] default: Connected successfully to server
[Nest] 35946 - 2022/05/08 06:01:03 LOG [RedisModule] default: Connected successfully to server
Update nestjs dependencies to latest version
Jest exits after running end-to-end app test.
Jest displays the following message and does not exit.
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.
nestjs-redis
(github:skunight/nestjs-redis#939f33a7) with @liaoliaots/nestjs-redis
.@liaoliaots/nestjs-redis
v5, use RedisManager instead of RedisService.@liaoliaots/nestjs-redis
5.1.0 & 3.1.1,Hi
I am trying to write Jest tests and use as useValue: redis-memory-server. But I get errors like
Nest can't resolve dependencies of the RedisManager (?). Please make sure that the argument Symbol() at index [0] is available in the RootTestModule context.
Potential solutions:
- If Symbol() is a provider, is it part of the current RootTestModule?
- If Symbol() is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing Symbol() */ ]
})
Maybe you have an idea how to fix it?
If needed, I can provide my jest file.
Hi! 👋
Firstly, thanks for your work on this project! 🙂
I would like to set up the redis module in a non-global way, so is there a chance we can make it configurable? Thanks!
Here is the diff that solved my problem:
diff --git a/node_modules/@liaoliaots/nestjs-redis/dist/redis/redis.module.js b/node_modules/@liaoliaots/nestjs-redis/dist/redis/redis.module.js
index 8d6de0a..d72312e 100644
--- a/node_modules/@liaoliaots/nestjs-redis/dist/redis/redis.module.js
+++ b/node_modules/@liaoliaots/nestjs-redis/dist/redis/redis.module.js
@@ -29,7 +29,7 @@ let RedisModule = RedisModule_1 = class RedisModule {
...redisClientProviders
];
return {
- global: true,
+ global: false,
module: RedisModule_1,
providers,
exports: [redis_manager_1.RedisManager, ...redisClientProviders]
This issue body was partially generated by patch-package.
I am currently getting a ClientNofFoundError if I am running my integration tests. However my config and setup seems to be correct as I am just following the example Repo:
redis.config.ts :
export default {
url: `redis://${process.env.REDIS_USER}:${redisSecret}@${process.env.REDIS_HOSTNAME}:${redisPort}/${process.env.REDIS_OPTIONS}`,
}
app.module.ts :
RedisModule.forRootAsync({
useFactory: async (configService: ConfigService) => configService.get('redis.config'),
inject:[ConfigService]
}),
dummy.repo.ts:
`export class DummyRepository implements IDummyRepository {
constructor(
@InjectRedis() private readonly redisClient: Redis.Redis,
private readonly logger: LoggerService
) {
this.logger.setContext(this.constructor.name)
}`
integration.spec.ts:
const moduleFixture = await Test.createTestingModule({ imports: [AppModule] }).compile();
client = moduleFixture.get<Redis.Redis>(getRedisToken('default'));
app = moduleFixture.createNestApplication();
Is there still something I am missing ?
As soon as I am trying to run my integration tests, I am getting this error:
Thanks in advance !
Hi! I'm getting "Connection is closed" error when i'm trying to send second request. For example:
await this.redis.ping(); // <-- "PONG"
await this.redis.ping(); // <-- UnhandledPromiseRejectionWarning: Error: Connection is closed.
Why is that happening? Plain ioredis works fine.
Your issue may already be reported!
Please search on the issue tracker before creating one.
AWS ElasticCache connection should be established without having an issue.
AWS Security Group's inbound rule is open to public (0.0.0.0).
RedisModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
config: {
host: 'aws-elastic-cache-url',
port: config.get('REDIS_PORT') || 6379,
password: config.get('REDIS_PASSWORD'),
},
}),
}),
I'm facing the following error.
[Nest] 77739 - 03/16/2023, 5:50:05 PM ERROR [RedisModule] default: connect ETIMEDOUT +10056ms
Error: connect ETIMEDOUT
at Socket.<anonymous> (/Users/x/Projects/workspace/backend/node_modules/ioredis/built/Redis.js:170:41)
at Object.onceWrapper (node:events:627:28)
at Socket.emit (node:events:513:28)
at Socket._onTimeout (node:net:562:8)
at listOnTimeout (node:internal/timers:564:17)
at processTimers (node:internal/timers:507:7)
If I try with my localhost redis, it works fine.
Hi @liaoliaots , thank you for all your hard work for this library
For a Jest test, Redis should close after test module (@nestjs/testing) encounters error during compilation.
Redis hangs after encountering error during test module compilation. testingModule
is undefined when error is encountered
TypeError: Cannot read properties of undefined (reading 'close')
147 |
148 | afterAll(async () => {
> 149 | await testingModule.close();
| ^
150 | });
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.
When there's no error, it is closed properly via afterAll() and everything is fine.
Saw a similar issue raised but its solution (setting closeClient
to true) did not work
testingModule = await Test.createTestingModule({
imports: [
RedisModule.forRoot({
config: {
url: `redis://localhost:6379`,
},
}),
TypeOrmModule.forFeature([
<missing required entity import>
])
]
}).compile();
afterAll(async () => {
await testingModule.close();
});
Create testing module via createTestingModule (@nestjs/testing) and leave out required entity import
Trying to ensure Jest exits properly after test run completion
配置上 目测没问题.. 加了redis后 跑不起来,
[Nest] 12832 - 2022/02/12 下午4:21:50 ERROR [ExceptionHandler] Nest can't resolve dependencies of the RedisModule (?, Symbol()). Please make sure that the argument Symbol() at index [0] is available in the RedisModule context.
Potential solutions:
Error: Nest can't resolve dependencies of the RedisModule (?, Symbol()). Please make sure that the argument Symbol() at index [0] is available in the RedisModule context.
Potential solutions:
in app.modules.ts:
imports: [
ConfigModule.forRoot({
envFilePath: '.env',
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
return {
type: configService.get('DATABASE_TYPE'),
host: configService.get('DATABASE_HOST'),
port: configService.get('DATABASE_PORT'),
username: configService.get('DATABASE_USERNAME'),
password: configService.get('DATABASE_PASSWORD'),
database: configService.get('DATABASE_NAME'),
synchronize: configService.get('DATABASE_SYNCHRONIZE'),
dropSchema: false,
keepConnectionAlive: true,
logging: configService.get('app.nodeEnv') !== 'production',
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
timezone: '+08:00', // 东八区
cache: {
duration: 60000, // 1分钟的缓存
},
// logging: true,
seeds: [__dirname + '/seeds/**/*{.ts,.js}'],
factories: [__dirname + '/factories/**/*{.ts,.js}'],
cli: {
entitiesDir: 'src',
migrationsDir: 'src/database/migrations',
subscribersDir: 'subscriber',
},
} as TypeOrmModuleAsyncOptions;
},
}),
RedisModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => (
{
closeClient:true,
config: {
host: configService.get('REDIS_HOST'),
port: configService.get('REDIS_PORT'),
password: configService.get('REDIS_PWD'),
db: configService.get('REDIS_DB'),
}
}
)
}),
ThrottlerModule.forRootAsync({
imports:[RedisModule],
inject: [RedisService],
useFactory(redisService: RedisService) {
const redis = redisService.getClient('default');
return { ttl: 60, limit: 10, storage: new ThrottlerStorageRedisService(redis) };
},
}),
AuthModule,
UserModule,
RoleModule,
ResourceModule,
ProjectModule,
CategoryModule,
MinioModule,
HumanResourceModule,
FileModule,
FinanceModule,
CaslModule,
RedisCacheModule,
// CacheModule.register()
],
controllers: [AppController],
providers: [
AppService,
// {
// provide:APP_GUARD,
// useClass:ThrottlerGuard,
// },
],
"@liaoliaots/nestjs-redis": "^5.2.0",
We would love to allow for the possibility for redis not being able to connect. We use redis mainly for caching purposes, and in the situation that our redis cluster should crash / be temporary down, we'd like our nest.js application not to crash.
I suggest adding an option that would allowFailedConnections
(for lack of a better word) which would simply output to the logger that it failed to boot and perhaps keep retrying in the background.
When calling the redis.get()
it would fallback to the behaviour it has, when redis did not find the key.
Thoughts?
@liaoliaots, can you provide an implementation of service unit-test documents?
I want to cover a test case on a service that injected with nestjs-redis
.
Mocking the Redis provider when running an e2e test should provide a mocked redis instance that does not try connection to a Redis server.
app.module.ts:
@Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
isGlobal: true,
}),
RedisModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (
configService: ConfigService,
): Promise<RedisModuleOptions> => {
const config = configService.get('redis'); // this also has namespace 'sipUsers'
return {
config,
};
},
}),
KamailioApiModule,
],
controllers: [AppController],
providers: [
AppService,
],
})
app.e2e-spec.ts
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
providers: [
{
provide: getRedisToken('sipUsers'),
useValue: mockedRedisService,
},
],
})
Running this test gives me this error, meaning the mock for the app module is not working:
[Nest] 75665 - 18/10/2022, 17:35:36 ERROR [RedisModule] sipUsers: connect ECONNREFUSED 127.0.0.1:6379
I also run a unit test for the service that uses the Redis module. Here the mock works perfectly.
Redis injected like this in my service:
export class KamailioApiService {
private kamailioApiUrl = this.configService.get('kamailioApi.url');
private kamailioApiKey = this.configService.get('kamailioApi.apiKey');
constructor(
private http: HttpService,
private configService: ConfigService,
@InjectRedis('sipUsers') private readonly redis: Redis,
) {}
...
The mock:
const module: TestingModule = await Test.createTestingModule({
providers: [
KamailioApiService,
{
provide: ConfigService,
useValue: mockedConfigService,
},
{
provide: getRedisToken('sipUsers'),
useValue: mockedRedisService,
},
loggerProvider(KamailioApiService.name),
],
imports: [HttpModule], // this is just a test to make tests run, dont know if we should mock this here already
}).compile();
So it's weird to me that it doesnt work when mocking it for the root App, But I cant figure out why since I mock other services in the same way for both my unit and e2e tests.
I just installed the latest version and imported redis module into my app.module and get this error
node_modules/@liaoliaots/nestjs-redis/dist/redis/common/redis.utils.d.ts:7:110 - error TS2304: Cannot find name 'PromiseSettledResult'.
7 export declare const quitClients: (clients: RedisClients) => Promise<[PromiseSettledResult<ClientNamespace>, PromiseSettledResult<"OK">][]>;
No response
RedisModule.forRoot({
config: {
host: 'redis',
port: 6379,
},
}),
run without any error!
here is nestjs info
yarn run v1.22.17
$ /home/node/app/node_modules/.bin/nest info
_ _ _ ___ _____ _____ _ _____
| \ | | | | |_ |/ ___|/ __ \| | |_ _|
| \| | ___ ___ | |_ | |\ `--. | / \/| | | |
| . ` | / _ \/ __|| __| | | `--. \| | | | | |
| |\ || __/\__ \| |_ /\__/ //\__/ /| \__/\| |_____| |_
\_| \_/ \___||___/ \__|\____/ \____/ \____/\_____/\___/
[System Information]
OS Version : Linux 5.15
NodeJS Version : v16.14.0
YARN Version : 1.22.17
[Nest CLI]
Nest CLI Version : 8.2.4
[Nest Platform Information]
platform-express version : 8.4.3
platform-fastify version : 8.4.3
microservices version : 8.4.3
schematics version : 8.0.9
throttler version : 2.0.1
passport version : 8.2.1
graphql version : 9.2.7
swagger version : 5.2.1
typeorm version : 8.0.3
testing version : 8.4.3
apollo version : 10.0.8
common version : 8.4.3
config version : 1.2.1
axios version : 0.0.7
core version : 8.4.3
cqrs version : 8.0.3
jwt version : 8.0.0
cli version : 8.2.4
Done in 2.18s.
8.4.3
"dependencies": {
"@casl/ability": "^5.4.3",
"@graphql-tools/utils": "^7",
"@liaoliaots/nestjs-redis": "^8.1.0",
"@nestjs/apollo": "^10.0.8",
"@nestjs/axios": "^0.0.7",
"@nestjs/common": "^8.0.4",
"@nestjs/config": "^1.0.1",
"@nestjs/core": "^8.0.4",
"@nestjs/cqrs": "^8.0.0",
"@nestjs/graphql": "^9.0.6",
"@nestjs/jwt": "^8.0.0",
"@nestjs/microservices": "^8.2.3",
"@nestjs/passport": "^8.0.0",
"@nestjs/platform-express": "^8.0.4",
"@nestjs/platform-fastify": "^8.0.4",
"@nestjs/swagger": "^5.0.9",
"@nestjs/throttler": "^2.0.0",
"@nestjs/typeorm": "^8.0.1",
"@types/bcrypt": "^3.0.0",
"@types/lodash": "^4.14.178",
"@types/passport": "^1.0.4",
"@types/validator": "^13.1.1",
"amqp-connection-manager": "^3.7.0",
"amqplib": "^0.8.0",
"apollo-server-fastify": "^3.4.0",
"axios": "^0.26.1",
"bcrypt": "^5.0.0",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"csvtojson": "^2.0.10",
"fastify-helmet": "^5.3.2",
"fastify-swagger": "^4.8.3",
"graphql": "^15.6.1",
"graphql-type-json": "^0.3.2",
"ioredis": "^5.0.4",
"jalali-moment": "^3.3.10",
"jsonata": "^1.8.5",
"kavenegar": "^1.1.4",
"knex": "^0.21.12",
"lodash": "^4.17.21",
"moment": "^2.29.1",
"nest-commander": "^2.3.5",
"nestjs-typeorm-paginate": "^3.1.3",
"order-id": "^2.1.2",
"otplib": "^12.0.1",
"passport": "^0.4.1",
"passport-custom": "^1.1.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"pg": "^8.5.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.0.0",
"typeorm": "^0.2.29",
"typeorm-polymorphic": "^0.0.3",
"typeorm-seeding": "^1.6.1"
},
"devDependencies": {
"@apollo/gateway": "^0.45.0",
"@nestjs/cli": "^8.2.4",
"@nestjs/schematics": "^8.0.8",
"@nestjs/testing": "^8.4.3",
"@types/express": "^4.17.8",
"@types/faker": "^5.5.9",
"@types/jest": "^26.0.15",
"@types/node": "^14.14.6",
"@types/passport-jwt": "^3.0.3",
"@types/passport-local": "^1.0.33",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.6.1",
"@typescript-eslint/parser": "^4.6.1",
"eslint": "^7.12.1",
"eslint-config-prettier": "^6.15.0",
"eslint-plugin-prettier": "^3.1.4",
"jest": "^26.6.3",
"prettier": "^2.1.2",
"supertest": "^6.0.0",
"ts-jest": "^26.4.3",
"ts-loader": "^8.0.8",
"ts-morph": "^12.0.0",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.0.5"
},
No response
No response
Redis Service is not exported from @liaoliaots/nestjs-redis module and how to use it now ?
RedisError: The redis client-provider 'Symbol(default)' was not found in the application context.
at RedisManager.getClient (/data/projects/portal-be/node_modules/@liaoliaots/nestjs-redis/dist/redis/redis-manager.js:26:19)
at new SmsService (/data/projects/portal-be/dist/app/sms/sms.service.js:24:35)
at Injector.instantiateClass (/data/projects/portal-be/node_modules/@nestjs/core/injector/injector.js:300:19)
at callback (/data/projects/portal-be/node_modules/@nestjs/core/injector/injector.js:48:41)
at async Injector.resolveConstructorParams (/data/projects/portal-be/node_modules/@nestjs/core/injector/injector.js:124:24)
at async Injector.loadInstance (/data/projects/portal-be/node_modules/@nestjs/core/injector/injector.js:52:9)
at async Injector.loadProvider (/data/projects/portal-be/node_modules/@nestjs/core/injector/injector.js:74:9)
at async Promise.all (index 4)
at async InstanceLoader.createInstancesOfProviders (/data/projects/portal-be/node_modules/@nestjs/core/injector/instance-loader.js:44:9)
at async /data/projects/portal-be/node_modules/@nestjs/core/injector/instance-loader.js:29:13
at async Promise.all (index 16)
at async InstanceLoader.createInstances (/data/projects/portal-be/node_modules/@nestjs/core/injector/instance-loader.js:28:9)
at async InstanceLoader.createInstancesOfDependencies (/data/projects/portal-be/node_modules/@nestjs/core/injector/instance-loader.js:18:9)
at async /data/projects/portal-be/node_modules/@nestjs/core/nest-factory.js:93:17
at async Function.asyncRun (/data/projects/portal-be/node_modules/@nestjs/core/errors/exceptions-zone.js:22:13)
at async NestFactoryStatic.initialize (/data/projects/portal-be/node_modules/@nestjs/core/nest-factory.js:91:13)
at async NestFactoryStatic.create (/data/projects/portal-be/node_modules/@nestjs/core/nest-factory.js:37:9)
at async bootstrap (/data/projects/portal-be/dist/index.js:17:17)
Need some other config?
"@liaoliaots/nestjs-redis": "^9.0.1",
nestjs 9.0.8
if app.enableShutdownHooks() is called, the following error will be thrown
[Nest] 32992 - 10/08/2022, 02:40:50 ERROR [NestApplicationContext] Error happened during shutdown
Error: Nest could not find Symbol() element (this provider does not exist in the current context)
at InstanceLinksHost.get (/xxx/node_modules/@nestjs/core/injector/instance-links-host.js:21:19)
at ModuleRef.find (/xxx/node_modules/@nestjs/core/injector/module-ref.js:39:55)
at ModuleRef.get (/xxx/node_modules/@nestjs/core/injector/module.js:351:28)
at RedisModule.onApplicationShutdown (/xxx/node_modules/@liaoliaots/nestjs-redis/dist/redis/redis.module.js:68:48)
at callAppShutdownHook (/xxx/node_modules/@nestjs/core/hooks/on-app-shutdown.hook.js:51:35)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at NestApplication.callShutdownHook (/xxx/node_modules/@nestjs/core/nest-application-context.js:208:13)
at process.cleanup (/xxx/node_modules/@nestjs/core/nest-application-context.js:146:17)
I'm trying to connect to my Digital Ocean hosted Redis database using this configuration:
RedisModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
return {
readyLog: true,
config: {
url: 'rediss://default:<password>@<host>:25061',
},
};
},
}),
I take the connection string from DO, and it is correct. But when I try to connect, I get an error:
var err = new errorClasses.AbortError(error_attributes);
^
AbortError: Redis connection lost and command aborted. It might have been processed.
at RedisClient.flush_and_error (/Users/***/Desktop/server/node_modules/redis/index.js:298:23)
at RedisClient.connection_gone (/Users/***/Desktop/server/node_modules/redis/index.js:603:14)
at Socket.<anonymous> (/Users/***/Desktop/server/node_modules/redis/index.js:231:14)
at Object.onceWrapper (node:events:641:28)
at Socket.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
at new Command (/Users/***/Desktop/server/node_modules/redis/lib/command.js:12:22)
at RedisClient.info (/Users/***/Desktop/server/node_modules/redis/lib/individualCommands.js:169:39)
at RedisClient.ready_check (/Users/***/Desktop/server/node_modules/redis/index.js:470:10)
at RedisClient.on_connect (/Users/***/Desktop/server/node_modules/redis/index.js:364:14)
at Socket.<anonymous> (/Users/***/Desktop/server/node_modules/redis/index.js:213:14)
at Object.onceWrapper (node:events:641:28)
at Socket.emit (node:events:539:35)
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1173:10)
I believe this error is related to SSL/TLS connection and configuration
Sorry if my problem is stupid or already solved. I am new to Redis
How to handle connection error with nestjs-redis?
For example I turn off my redis container and it should throw an error that it can't connect to redis
Trying to set up Sentinel, but I am having some issues.
My docker-compose.yaml:
redis-sentinel:
image: bitnami/redis-sentinel:latest
restart: always
ports:
- 26379:26379
networks:
- nestjs-network
environment:
- REDIS_MASTER_HOST=redis
redis:
image: 'bitnami/redis:latest'
environment:
- ALLOW_EMPTY_PASSWORD=yes
networks:
- nestjs-network
ports:
- 6379:6379
Sentinel seems to be up and running:
redis-sentinel 14:59:36.90
redis-sentinel 14:59:36.94 Welcome to the Bitnami redis-sentinel container
redis-sentinel 14:59:36.98 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-redis-sentinel
redis-sentinel 14:59:37.02 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-redis-sentinel/issues
redis-sentinel 14:59:37.06
redis-sentinel 14:59:37.09 INFO ==> ** Starting Redis sentinel setup **
redis-sentinel 14:59:37.41 INFO ==> Initializing Redis Sentinel...
redis-sentinel 14:59:37.48 INFO ==> Configuring Redis Sentinel...
redis-sentinel 14:59:38.35 INFO ==> ** Redis sentinel setup finished! **
redis-sentinel 14:59:38.50 INFO ==> ** Starting Redis Sentinel **
1:X 10 Apr 2022 14:59:38.607 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:X 10 Apr 2022 14:59:38.608 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
1:X 10 Apr 2022 14:59:38.608 # Configuration loaded
1:X 10 Apr 2022 14:59:38.611 * monotonic clock: POSIX clock_gettime
1:X 10 Apr 2022 14:59:38.621 * Running mode=sentinel, port=26379.
1:X 10 Apr 2022 14:59:38.650 # Sentinel ID is d1cb69092f21a9c96e793f94cc937c2828b8ab04
1:X 10 Apr 2022 14:59:38.651 # +monitor master mymaster 172.23.0.4 6379 quorum 2
My configuration:
return {
readyLog: true,
commonOptions: {
name: 'mymaster',
sentinels: [
{
host: "localhost", // I am running npm locally (not in docker)
port: 26379,
},
],
},
config: [
{
// get master node from the sentinel group
role: 'master',
},
{
// get a random slave node from the sentinel group
role: 'slave',
},
],
}
But I am getting error:
[Nest] 7506 - 04/10/2022, 5:08:21 PM ERROR [RedisModule] default: All sentinels are unreachable. Retrying from scratch after 130ms.
Error: All sentinels are unreachable. Retrying from scratch after 130ms.
What am I missing here?
Error: Nest can't resolve dependencies
NestJS version: 7.6
import { Redis } from 'ioredis';
import { InjectRedis } from '@liaoliaots/nestjs-redis';
constructor(@InjectRedis('cache') private readonly clientCache: Redis)
Heya!
We are using your awesome module in production on two projects, thank you so much
Please shed a light on module compatibility with newly released nestjs8 and write a migration guide if any
it was removed in this commit
076cdc3#diff-d5a4b3a0309f2337144861084c1014523cced561eb722cb9684c63f5e41e0567L5
it probably should be exported from here
076cdc3#diff-2780ab9bea6364cc71f6004bbc2aed48cb3379af9f7b3d4e6377b6a7560c0757R2
but for some reason was lost
Nest wont build
`node_modules/@liaoliaots/nestjs-redis/dist/cluster/common/cluster.utils.d.ts:8:73 - error TS2304: Cannot find name 'PromiseSettledResult'.
8 export declare const quitClients: (clients: ClusterClients) => Promise<[PromiseSettledResult<ClientNamespace>, PromiseSettledResult<'OK'>][]>;
node_modules/@liaoliaots/nestjs-redis/dist/cluster/common/cluster.utils.d.ts:8:112 - error TS2304: Cannot find name 'PromiseSettledResult'.
8 export declare const quitClients: (clients: ClusterClients) => Promise<[PromiseSettledResult<ClientNamespace>, PromiseSettledResult<'OK'>][]>;
`
"node": "16.13.0",
"yarn": "1.22.x",
"npm": "8.1.x"
"@liaoliaots/nestjs-redis": "^5.1.0",
"@types/ioredis": "^4.28.1",
"ioredis": "^4.28.0",
"typescript": "^4.4.4"
v8 of nest modules
Can i use client.json.set
with this library?
main
branch failed. 🚨I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here are some links that can help you:
If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.
The npm token configured in the NPM_TOKEN
environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/
.
If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.
Please make sure to set the NPM_TOKEN
environment variable in your CI with the exact value of the npm token.
Good luck with your project ✨
Your semantic-release bot 📦🚀
Thank for your contribute, so i have a issue when implement.
when i use cluster module, if one node timeout connect, i can not get data from another nodes and get error.
My application works correctly accessing only one instance of Redis, but I am not able to configure my application with Redis Sentinel.
I tried to follow the example of the project's repositories, but it seems that nothing happens.
My module looks like this:
import { Module } from '@nestjs/common';
import { RedisModule } from '@liaoliaots/nestjs-redis';
import { NestRedisService } from './nestjs-redis.service';
import { RedisConfigService } from './nestjs-redis.config.service';
@Module({
imports: [
RedisModule.forRootAsync({
useClass: RedisConfigService,
}),
],
providers: [NestRedisService],
exports: [NestRedisService],
})
export class NestjsRedisModule {}
My connection configuration file looks like this:
import { Injectable } from '@nestjs/common';
import {
RedisOptionsFactory,
RedisModuleOptions,
} from '@liaoliaots/nestjs-redis';
import { InjectPinoLogger } from 'nestjs-pino/InjectPinoLogger';
import { PinoLogger } from 'nestjs-pino';
export interface ErrnoException extends Error {
errno?: number;
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
@Injectable()
export class RedisConfigService implements RedisOptionsFactory {
constructor(
@InjectPinoLogger(RedisConfigService.name)
private readonly logger: PinoLogger,
) {}
async createRedisOptions(): Promise<RedisModuleOptions> {
const logger = this.logger;
return {
config: {
role: 'master',
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD,
maxRetriesPerRequest: 0,
onClientCreated(client) {
client.on('error', (error: ErrnoException) => {
logger.info(
{ description: '[Create Conection][Error]' },
JSON.stringify(error),
);
});
},
retryStrategy(times) {
const delay = Math.min(times * 50, 2000);
return delay;
},
},
};
}
}
Are these my Redis and Sentinel servers?
Master - 10.1.2.3 - 6379 - has password
Slave - 10.1.2.4 - 6379 - has password
Slave - 10.1.2.5 - 6379 - has password
Sentinel - 10.1.2.3 - 26379 - has no password
Sentinel - 10.1.2.4 - 26379 - has no password
What would be the best way to adapt the code above to connect with Redis sentinel?
main
branch failed. 🚨I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here are some links that can help you:
If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.
The npm token configured in the NPM_TOKEN
environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/
.
If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.
Please make sure to set the NPM_TOKEN
environment variable in your CI with the exact value of the npm token.
Good luck with your project ✨
Your semantic-release bot 📦🚀
code:
RedisModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
return {
config: {
url: configService.get('redis.url'),
},
};
},
}),
but it is failed by the error below
Error: Nest can't resolve dependencies of the TemplateService (?). Please make sure that the argument Model at index [0] is available in the TemplateModule context.
Potential solutions:
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.