Home > OS >  Value object static Factory
Value object static Factory

Time:11-16

I have some problematic for now that i want to know ur opinions. First, i have a userPassword which represent a value object within my user domain model. i would like to validate 2 cases when creating my userPassword object :

  • Not empty value of password

  • Hash the given value Thus, i don't really know the best approach to achieve it. Now that the problem was exposed, take a look at my code below :

    export class UserPassword {
      private readonly value:string
    
     private  constructor(value: string) {
    
         this.value =  value
     }
      public getValue():string {
          return this.value
      }
    
      // My static factory in which i want to apply my validations cases
    
      static create(password: string):UserPassword {
          // Need to be implemented
      }
      private async hashPassword(password: string):Promise<string>{
         return await bcrypt.hash(password,10)
      }
      async comparePassword(password:string):Promise<boolean> {
          let hashed: string = this.value
          return await bcrypt.compare(password, hashed)
      }
    

    }

CodePudding user response:

For validations purposes, i just done some verifications before creating my password object. Because i think that it's always relevant to defined validation logic in the object contruction. So here is my solution:

export class UserPassword {
    private readonly value:string

     constructor(value: string) {
        if (value === "") {
            throw new UserInputError("Password must be filled")
        }
        else {
            this.hashPassword(value).then(r => console.log(r))
            this.value =  value
        }
   }
    public getValue():string {
        return this.value
    }

    private async hashPassword(password: string):Promise<string>{
        return bcrypt.hash(password,10)
    }
    async comparePassword(password:string):Promise<boolean> {
        let hashed: string = this.value
        return  bcrypt.compare(password, hashed)
    }
}

CodePudding user response:

Something like this? I mean if you want to be super sure, never store, in memory neither, the clear value of the password

// My static factory in which i want to apply my validations cases

  static async create(password: string):UserPassword {
      if (!password || password.trim().length() == 0) {
           throw Exception("password not valid")
      }
      var hash = await bcrypt.hash(password,10)
      return new UserPassword(hash)
  }
  • Related