我正在尝试通过Nest / TypeORM构建SAAS产品,并且需要按子域配置/更改数据库连接。
customer1.domain.com => connect to customer1 database
customer2.domain.com => connect to customer2 database
x.domain.com => connect to x database
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点 ?使用拦截器或请求上下文(或Zone.js)?
我不知道如何开始。有人已经这样做了吗?
WIP:我目前在做什么:
在所有路由上创建中间件以将子域注入res.locals(实例名称)并创建/警告typeorm连接
import { Injectable, NestMiddleware, MiddlewareFunction } from '@nestjs/common';
import { getConnection, createConnection } from "typeorm";
@Injectable()
export class DatabaseMiddleware implements NestMiddleware {
resolve(): MiddlewareFunction {
return async (req, res, next) => {
const instance = req.headers.host.split('.')[0]
res.locals.instance = instance
try {
getConnection(instance)
} catch (error) {
await createConnection(instance)
}
next();
}; …Run Code Online (Sandbox Code Playgroud)