[英]Nestjs resolve custom startup dependency
I have this factory which resolves redis: 我有这个工厂来解决redis:
import {RedisClient} from "redis";
export const RedisProvider = {
provide: 'RedisToken',
useFactory: async () => {
return new Promise((resolve, reject) => {
let redisClient = new RedisClient({
host: 'resolver_redis'
});
redisClient.on('ready', function () {
resolve(redisClient);
});
});
}
};
But in addition to that, i wanna check if a specific key exists in redis, and if its not i want to retrive it using microservices, but for that i need to inject the microservices "client", i wanna change it to someting like that: 但是除此之外,我想检查redis中是否存在特定的密钥,如果不是,我想使用微服务检索它,但是为此我需要注入微服务“客户端”,我想将其更改为类似的东西:
import {RedisClient} from "redis";
export const RedisProvider = {
provide: 'RedisToken',
useFactory: async () => {
return new Promise((resolve, reject) => {
let redisClient = new RedisClient({
host: 'resolver_redis'
});
redisClient.on('ready', async function () {
let campaigns = await redisClient.get('campaigns');
if ( ! campaigns) {
// Note: "client" is not available in this scope
client.send('get:campaigns').subscribe(async function (campaigns) {
await redisClient.set('campaigns', campaigns);
resolve(redisClient);
});
}
else {
resolve(redisClient);
}
});
});
}
};
the only problem is that i dont have access to the "client", or do i? 唯一的问题是我没有访问“客户端”的权限,或者我可以吗? it can also be anther provider if it makes more sense, but then i will also need priority for loading the providers, i am doing this because the application requires this data for startup stuff 如果更有意义,它也可以是另一个提供程序,但是我也需要优先级来加载提供程序,我这样做是因为应用程序需要此数据来启动启动程序
I don't recommend adding more logic in providers factory, since it could be more controlled in the consumer of this provider ie: the services
我不建议在提供者工厂中添加更多逻辑,因为可以在此提供者的使用者中对其进行更多控制,即: services
in your services code you could do something like this 在您的服务代码中,您可以执行以下操作
import { Component, Inject, OnModuleInit } from '@nestjs/common';
...
@Component()
export class MyService implements OnModuleInit {
constructor(@Inject(REDIS_TOKEN) private readonly redis: RedisClient) {}
onModuleInit() {
const campaigns = await this.redis.get('campaigns');
...
}
}
I assume that REDIS_TOKEN
is constant saved on constants.ts
file and equal to RedisToken
. 我假设REDIS_TOKEN
是常量保存在constants.ts
文件中,并且等于RedisToken
。
this will be more controlled. 这将受到更多控制。 the code of checking for the campaigns
key will be executed once your Module init. 模块初始化后,将执行检查campaigns
密钥的代码。
for more information about Module Lifecycle checkout: Modules Lifecycle 有关模块生命周期检出的更多信息: 模块生命周期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.