Search code examples
typescriptdependency-injectionnestjs

Nestjs - Manually instantiate a class with dependencies on useFactory


suppose I have two classes like this

@Injectable({ scope: Scope.DEFAULT })
class Service {
    
    constructor() {}
    // ...
}

@Injectable()
class OtherService {
    param: T;

    constructor(readonly service: Service, param: T) {}

    // ... 
}

And I'm triying to dinamically instantiate the last class using a factory

const otherServiceFactory = {
    provide: "TOKEN",
    scope: Scope.Request,
    useFactory: (req: Request) => {
        const param = req.headers["foo"];
        return new OtherService(/* ts expects an instance of Service here */ , param)
    },
    inject: [REQUEST]
}

As the comment said, at the moment of creating the instance ts expects, correctly, an instance of Service. The problem is I rather not mess up with the DI tree, so I don't want to instantiate Service. I was able to hack this around by setting the param later instead of asking in the constructor, so I don't need the factory anymore, but feels pretty sub-optimal. Any suggestions?

Thanks


Solution

  • You can add Service to the inject array, and get the instance of Service that Nest creates, then pass it to OtherService so that you have everything required to create the class.

    const otherServiceFactory = {
        provide: "TOKEN",
        scope: Scope.Request,
        useFactory: (req: Request, service: Service) => {
            const param = req.headers["foo"];
            return new OtherService(service, param)
        },
        inject: [REQUEST, Service]
    }