I have created a multitenant app in NestJs using a connection factory where we inject a connection for each request. I have spent several days debugging this but no luck till now.
This is the connection factory
export const connectionFactory = {
provide: CONNECTION,
scope: Scope.REQUEST,
useFactory: (request: Request) => {
console.log('request', request)
if (!request) {
throw new Error('Request object is undefined');
}
const { subdomain } = request.req;
if (subdomain) {
return getTenantConnection(subdomain);
}
return null;
},
inject: [REQUEST],
};
@Global()
@Module({
providers: [connectionFactory],
exports: [CONNECTION],
})
export class TenancyModule { }
This is validate
method in my JwtStrategy
async validate(req: Request, payload: any): Promise<any> {
const { jti } = payload;
const contextId = ContextIdFactory.getByRequest(req);
this.authService = await this.moduleRef.resolve(AuthService, contextId);
try {
const user = await this.authService.validateAccessToken(jti);
console.log('here')
if (!user) {
throw new UnauthorizedException();
}
return user;
} catch (error) {
console.error('Error validating access token:', error);
throw new UnauthorizedException();
}
}
I never see the here
console because the request object in connectionFactory
is undefined. I have logged the request there and I can see in my console that first time request is logged correctly, I get the subdomain and then the connection is fine but I don’t know why when I call validateAccessToken
the connectionFactory
is called again but now the request is undefined.
This is happening only after user is logged in, the login functionality works as expected.