'How to create a custom class in NestJS and work with the instance of the class

I'm trying to create a helper class in NestJS which i can use in every file. I tried to create the following class:

export class Logging {
  public status: string;
  private currentLog: Model<LogDocument>;

  constructor(@InjectModel(Log.name) readonly log?: Model<LogDocument>) {
    // Create a new log item when new instance of class is created
    this.currentLog = new this.log({
      title: 'New Log',
      status: SyncStatusType.IN_PROGRESS,
      startTime: new Date(),
    });
  }

  public addCrashLog() {
    // Update current log
  }

  public addSuccessLog() {
    // Update current log
  }

  public finish() {
    // Set status and update log
  }
}

I want to be able to use this class in every other file and create a new instance of the class if necessary.

const newLog = new Logging();
newLog.addCrashLog();
....

Does someone have an idea how I can archive that with NestJS? Because I'm always having problems with dependency injection in NestJS when I'm trying to create a custom class.



Solution 1:[1]

First off, don't add the Logging class to any providers array, as that's what will tell Nest to create the instance. Next, if you're passing the values yourself, you don't need the @InjectModel() there's no need, as you're creating the class yourself. Lastly, just use the class as your example already shows, using the new keyword and handling the instantiation yourself. That should be all there is to it

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jay McDoniel