jeudi 19 novembre 2015

Absracting class using mongoose

I m developping an application in which I need to have some abstraction.

I mean there, that I would like to "simulate" an interface behaviour like creating a contract inside of my concrete classes.

Actually, dealing with Users, I'm having a UserMongoRepository class with the contract implemented :

  • getAll() returns the full list of users by promise
  • getById(id) returns the user concerned by promise
  • save(user) saves the user by promise
  • ... etc

I have te same methods implemented inside of the UserMysqlRepository (allowing me to switch behaviour when a change is needed.

Problem

My problem is that I m dealing with Mongoose that doesn't act like a datamapper, but more like an active record.

It means that my implementation of save(user) would be a bit weird like following :

save(user){
    let mongooseUser = this.convert(user);
    return user.save();
  }

The convert method allows me to switch from a standard Model to a specific Mongoose model. It allows me, again, to have some abstraction and to don't have to rewrite my full application data access.

My real problem is when I try to unit test my full class :

import MongooseUser from '../../auth/mongooseModel/MongooseUser';
/**
* UserMongoRepositoryclass
*/
export default class UserMongoRepository{

  /**
  * Create an UserMongoRepository
  */
  constructor(){

  }

  /**
  * Convert a User to a MongooseUser
  */
  convert(user){
    return new MongooseUser({email:user.mail,password:user.password,firstname:user.firstName, lastname:user.lastName});
  }


  findById(id){
    return MongooseUser.find({id:id});
  }


  save(user){
    return user.save();
  }


}

In a standard way, I would inject my DAO inside of my constructor, and being able to mock it.

In the case of mongoose, it's a bit distburding, because the element that makes the job isn't an instanciated object (so that I can mock it) but a class definition imported at the top of the document.

Solutions

Should I pass the MongooseUser class definition as a parameter inside of the constructor ?

Implying that I will have this code inside of the convert method :

let user = new this.MongooseUser({})

Have you got a better idea, to abstract mongoose behaviour in data mapper way ?

I don't want to use another module, it's, in my sense, the most advanced one with NodeJS...

Thanks for your help

Aucun commentaire:

Enregistrer un commentaire