NestJS请求范围内的多个数据库的多租户

NestJS请求范围内的多个数据库的多租户

本文介绍了NestJS请求范围内的多个数据库的多租户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望使用NestJS 6的新请求注入范围功能实现多租户NestJS解决方案.

Looking to implement a multi-tenant NestJS solution using the new request injection scope feature of NestJS 6.

对于任何给定的服务,我都认为我可以做这样的事情:

For any given service I assume I could do something like this:

@Injectable({scope: Scope.REQUEST})
export class ReportService implements OnModuleInit { ... }

然后,在构造函数中,根据请求确定租户,连接到适当的数据库,并为新连接实例化存储库.

then, in the constructor, determine the tenant from the request, connect to the appropriate database, and instantiate repositories for the new connection.

我想知道这是否是最简单的方法吗?

I'm wondering if this is the most straightforward way to go about it?

代替更新每个服务,是否可以覆盖请求的连接提供者和范围 ?

Instead of updating each service, is it possible to override the connection provider and scope that to the request?

推荐答案

这就是我们最终要做的...

Here's what we ended up doing...

  1. 创建绑定到请求范围的简单全局TenancyModule:

tenancy.module.ts

import { Global, Module, Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { getConnection } from 'typeorm';

const connectionFactory = {
  provide: 'CONNECTION',
  scope: Scope.REQUEST,
  useFactory: (req) => {
    const tenant = someMethodToDetermineTenantFromHost(req.headers.host);
    return getConnection(tenant);
  },
  inject: [REQUEST],
};

@Global()
@Module({
  providers: [connectionFactory],
  exports: ['CONNECTION'],
})
export class TenancyModule {}
  1. 将特定于请求的'CONNECTION'注入到模块服务中,以从中检索存储库:
  1. Inject request-specific 'CONNECTION' into module services from which to retrieve repositories:

user.service.ts

...
@Injectable({scope: Scope.REQUEST})
export class UserService {
  private readonly userRepository: Repository<User>;

  constructor(@Inject('CONNECTION') connection) {
    this.userRepository = connection.getRepository(User);
  }

这篇关于NestJS请求范围内的多个数据库的多租户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:42