When I try to get the repository where my sessions are stored(the second line of code) it throws the error "Connection "default" was not found" I initialized TypeORM in the App.module.ts file
main.ts
const app = await NestFactory.create(AppModule);
const sessionRepository = getRepository(Session);
app.useWebSocketAdapter(new WebsocketAdapter(app));
app.enableCors({ origin: 'http://localhost:5173', credentials: true });
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
name: 'session_cookie_name',
cookie: {
maxAge: 1000 * 60 * 60 * 24,
},
store: new TypeormStore().connect(sessionRepository),
}),
);
app.use(passport.initialize());
app.use(passport.session());
await app.listen(3000);
App.module.ts
@Module({
imports: [
AuthModule,
UsersModule,
ConfigModule.forRoot({
envFilePath: '.env.development',
}),
PassportModule.register({
session: true,
}),
TypeOrmModule.forRoot({
type: 'mysql',
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
entities: [User, Session],
synchronize: true,
logging: false,
}),
GatewayModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
Can someone explain where I did wrong?
Rather than using getRepository()
from TypeORM you can use app.get()
from the NestApplication
to get a provider. Pass in getRepositoryToken(Session)
and { strict: true }
to get the same repository as getRepository(Session)
, but now from the DI container.
Note: to do this, TypeormModule.forFeature([Session])
must also be in an imports
array in the application, as this sets up the token for getRepositoryToken()