nestjs - 在运行时替换提供者对象
问题描述
假设我有一个提供与某物的连接的模块。
export const CONN string = 'CONN';
@Global()
@Module({})
export class ConnModule implements OnApplicationShutdown {
constructor(@Inject(CONN) private readonly conn: Connection) {}
onApplicationShutdown() {
this.conn.close();
}
static forRoot(options): DynamicModule {
const connectionProvider = {
provide: CONN,
useFactory: async (): Promise<Connection> => {
const connection = new Connection(options);
await connection.establish();
return connection;
},
};
return {
module: ConnModule ,
providers: [connectionProvider],
exports: [connectionProvider],
};
}
}
此连接通过应用程序使用:
export class AService {
constructor(
@Inject(CONN) protected readonly conn: Connection,
) {}
someMethod() {
this.conn.doSomething(); // this may get 401ed
}
export class BService {
constructor(
@Inject(CONN) protected readonly conn: Connection,
) {}
otherMethod() {
this.conn.doSomethingElse(); // this may get 401ed
}
这是与第 3 方应用程序的连接,它可能会在需要我们重新验证/重新创建连接的任何时候开始返回 401。
如何在出错时创建新连接并替换所有正在使用它的模块的当前提供程序?
就像是:
OnConnectionUnauthorizedException ->
create a new Connection ->
replace the current stale connection object that CONN provides with a new one ->
retry the original action
谢谢!
解决方案
这听起来与我有关。因为很难与外界交流您的应用程序的状态。此外,在重新建立连接期间处理事件/请求会发生什么?您将处理很多意外的复杂性。至少考虑健康检查以公开您的应用程序的状态。
然而,有一个我可以想象的解决方案:不是提供连接,而是提供一个服务,将连接保存在私有字段中。创建一个getConection
方法,可能与断开连接的时间间隔异步,然后返回连接。这样您就不必替换注入的值。
此外,我真的不鼓励替换注入的值。因为这真的很难与可能依赖于该值的代码进行通信。(“例如,嘿这里是一个新实例)。
export class ConnectionService {
connection: Conection | undefined;
// Pro Tip: make getConnection async and leverage e.g. Promise.race to implement
// a timeout so that if the connection is down this code e.g. delays 5 seconds and
// if the connection gets re-established, answers with the new connection or throws
// a "Couldnt reconnect" error
getConnection(){
return this.connection;
}
}
此解决方案应该是您最后的手段,相反,您应该挑战所需重新连接的来源。
推荐阅读
- python - 由于“转换”,导入 matplotlib.animation 失败
- python - 为什么这个 oneliner 给我语法错误?
- node.js - 如何在 Nodejs 中将文件从 Web 下载到服务器端并在 ReactJs 中将其发送到客户端?
- r - 运行后测量R中代码块的运行时间
- python - 如何使用 Python 从 TFS REST API 获取信息?
- python-2.7 - 如何拆分字符串的一小部分?
- c# - 反序列化序列化的 json 字符串列表
- javascript - MaxListenersExceededWarning:可能的 EventEmitter 内存泄漏检测
- c# - C# 表达式检查成员/属性是否为空
- bash - 在特定模式下方或上方几处插入一行