lundi 11 avril 2022

What's the best practice for reusing functions on different models in NestJS?

I have declared some functions for a MongoDB collection Model A, now I want to create another collection Model B and most of the functions in Model A can be reused for Model B. Currently, I fall into a situation where I have to repeat myself recreating these functions just for a different model. What's the best practice to reuse these functions on a different model (How to improve my code)? I am using NestJS framework. Example code that I have:

export class Service {
  constructor (
    @inject('ModelA')
    private modelA: Model<IModelA>,
    @inject('ModelB')
    private modelB: Model<IModelB>,
  ){}
  
 public async findModelA() {
   return await this.modelA.find().exec();
 }

 // How to avoid repeating creating the same functions here?

 public async findModelB() {
   return await this.modelB.find().exect();
 }
}

The repeated functions which are similar to the above example are all over the place. So I really want to get rid of this pain. Thank you in advance for the help!

Aucun commentaire:

Enregistrer un commentaire