In NestJS how do I create a new instance of a class and have dependencies injected?

Viewed 19

I have a set of classes that deal with processing items that are added into a database table (async_item).

Sometimes this will be started from a controller endpoint and sometimes it will be triggered by something else (such as listening to an SQS endpoint).

The call looks like this:

AsyncItemDispatcherFactory.getAsyncItemDispatcher(this.asyncItemService)
    .processItem(createOrFindByExternalIdReturn.asyncItemEntity.id)

The dispatcher class from getAsyncItemDispatcher() then uses a switch statement on the item type to decide which handler to instantiate and pass the item to for processing. These handlers could be quite complex and require many services - here is an example skeleton one:

import { ProjectService } from '../../../admin/project/project.service'
import { VintageService } from '../../../admin/vintage/vintage.service'
import { AsyncItemEntity } from '../../../entity/async-item.entity'
import { AsyncItemService } from '../../async-item.service'
import { IAsyncItemHandler } from './IAsyncItemHandler'

export class RegistryCreditsReceivedHandler implements IAsyncItemHandler {
    constructor(
        private readonly asyncItemService: AsyncItemService,
        private readonly projectService: ProjectService,
        private readonly vintageService: VintageService,
    ) {}

    handleItem(asyncItem: AsyncItemEntity): void {
        // perform the actions to handle the credits received call
    }

}

This depends on 3 services but it could be many more.

This is the switch statement but it currently uses new to instantiate the new class but this obviously doesn't perform any DI:

        // pass it to its handler to be processed
        switch (asyncItem.type) {
            case AsyncItemTypes.REGISTRY_CREDITS_RECEIVED:
                new RegistryCreditsReceivedHandler().handleItem(asyncItem)
                break
            default:
                throw new Error(`Unknown async_item.type: ${asyncItem.type} id: ${asyncItem.id}`)
        }

How can I use the DI in NestJS to create a new instance of a class and have the dependencies injected?

The alternate is that the dispatcher knows about all the dependencies of each of the handlers, which is likely to become a very large list, which just feels wrong...

0 Answers
Related