#How to clean connection in request scoped service?

2 messages · Page 1 of 1 (latest)

jagged ferry
#
@Injectable({ scope: Scope.REQUEST })
export class RequestContextService {
    private connection = new Connection();

I have a request scoped service, I am creating some connection... after request I need to close connection. How can do It? There is a onModuleDestroy but it is work only for app shutdown.

twilit goblet
#

That's a good question. I couldn't find any lifecycle event for such cases. In the docs it only mentions the instances are "garbage-collected" after the request has completed processing, which suggests there's no dedicated cleanup mechanism. But I haven't checked the source code.

I'd probably use the request (https://docs.nestjs.com/fundamentals/injection-scopes#request-provider) to register an event listener in the service constructor:

request.raw.once('close', () => {this.connection.close()})