cvhberger
cvhberger

Reputation: 153

NestJS: Resolving dependencies in NestMiddleware?

I'm trying to combine express-session with a typeorm storage within NestJS framework. Therefore I wrote a NestMiddleware as wrapper for express-session (see below). When I start node, NestJS logs the following

Error message:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Nest can't resolve dependencies of the SessionMiddleware (?). Please verify whether [0] argument is available in the current context.

Express is not started (connection refused), but the Sqlite DB (where the sessions should be stored) is created (also a session table, but not the columns).

To me it looks like there is a special problem in resolving dependencies with @InjectRepository from nestjs/typorm-Module. Does anyone have a hint?

Code:

import { Middleware, NestMiddleware, ExpressMiddleware } from '@nestjs/common';
import * as expressSession from 'express-session';

import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TypeormStore } from 'connect-typeorm';

import { Session } from './session.entity';

@Middleware()
export class SessionMiddleware implements NestMiddleware {
  constructor(
    @InjectRepository(Session)
    private readonly sessionRepository: Repository<Session>
  ) {}

  resolve(): ExpressMiddleware {
    return expressSession({
      store: new TypeormStore({ ttl: 86400 }).connect(this.sessionRepository),
      secret: 'secret'
    });
  }
}

Upvotes: 2

Views: 1752

Answers (1)

cvhberger
cvhberger

Reputation: 153

It was my fault. Had the middleware in a module, but was configuring the session middleware at the app module level. On that level the following import statement was missing:

TypeOrmModule.forFeature([Session])

Moved now everything to non-app module including middleware configuration. That solved the problem.

Upvotes: 2

Related Questions