Instead of Singletons, I want to create dynamically class instances in NestJs.
I found two ways:
1) Directly create the class (ChripSensor is then not @Injectable)
import { ChirpSensor } from './chirp-sensor/chirp-sensor';
@Injectable()
export class SensorsService {
registeredSensors: any;
constructor(
@InjectModel('Sensor') private readonly sensorModel: Model<ISensor>,
private i2cService: I2cService) {
const sensors = this.i2cService.getSensors();
sensors.forEach((sensor) => {this.registeredSensors[sensor._id] = new ChirpSensor({name: sensor.name})});
}
I'm wondering if that is consistent with the DI way of nest.js
2) The second solution would be via a factory, but here I don't know how to pass the options.
export const chirpFactory = {
provide: 'CHIRP_SENSOR',
useFactory: (options) => {
console.log('USING FACTORY CHIRP, options', options)
if (process.env.SIMULATION === 'true') {
return new ChirpSensorMock(options);
}
else {
return new ChirpSensor(options);
}
}
};
Not quite sure how to continue here/ inject the factory properly as the examples create the object in the constructor without options?
Question:
What is the NestJs way to create those class instances?
Edit - for B12Toastr
Module - get the Mock or Original on Compile time
providers: [
{
provide: 'CHIRP_SENSOR',
useValue: process.env.SIMULATION === 'true'
? ChirpSensorMock
: ChirpSensor
},
],
Sensor Service
@Injectable()
export class SensorsService {
registeredSensors: any;
constructor(
@Inject('CHIRP_SENSOR') private ChirpSensorClass: any, // any works but ChirpSensorMock | ChirpSensor not
private i2cService: I2cService
) {
const sensors = this.i2cService.getSensors();
sensors.forEach((sensor) => {this.registeredSensors[sensor._id] = new ChirpSensorClass({name: sensor.name})});
}