I am developing a link shortener, and for my backend I have a CRUD REST API to handle authentication and creating shortened links etc., and I also want to handle redirects for the shortened URLs, but I do not want them to have the same path as my API endpoints (e.g. /api/v1/) since I am using setGlobalPrefix for my API. After doing some research online I came across the following Github issue which gave me a solution to my problem:
async function bootstrap() {
const server = new ExpressAdapter();
const apiFactory = new NestFactoryStatic();
const apiApp = await apiFactory.create(ApiModule, server);
apiApp.setGlobalPrefix('api/v1');
await apiApp.init();
const redirectFactory = new NestFactoryStatic();
const redirectApp = await redirectFactory.create(RedirectModule, server);
await redirectApp.init();
http
.createServer(server.getInstance())
.listen(process.env.PORT || 3000);
}
bootstrap();
But I came across another issue, I need access to my database in my RedirectModule, I already have a LinkRepository made for my REST API, but I couldn't import it to the RedirectModule, here is the code for ApiModule and what I've already tried.
@Module({
imports: [TypeOrmModule.forRoot(typeOrmConfig), LinksModule, AuthModule],
controllers: [LinksController],
providers: [],
})
export class ApiModule {}
With RedirectModule just trying to import LinkRepository as a feature like so:
@Module({
imports: [TypeOrmModule.forFeature([LinkRepository])],
controllers: [RedirectController]
})
export class RedirectModule {}
I get the following error:
Nest can't resolve dependencies of the LinkRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.
Potential solutions:
- If Connection is a provider, is it part of the current TypeOrmModule?
- If Connection is exported from a separate @Module, is that module imported within TypeOrmModule?
@Module({
imports: [ /* the Module containing Connection */ ]
})
So I have tried importing ApiModule into RedirectModule, and also exporting TypeOrmModule.forRoot(typeOrmConfig) in a seperate file and importing that into both modules, but then I get an error that tells me a connection already exists: AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.
So, how can I share the connection across the two seperate modules? Looking at Nest's documentation didn't help, because it assumes all modules are part of one big root module, which is not what I'm trying to do.
Edit: So it looks like the main issue is sharing the module across application, since I am creating 2 applications with different factories it will try to reconnect again to the database since it appears that modules are singletons only within the same app. Is there some work around to this? Or alternatively, another way to achieve what I'm trying to do? (Different URL prefix for one specific module)