Creating Value Objects with a Static Factory Method

Looking for some advice on a current issue I'm facing. I have a userPassword value object in my user domain model and want to validate two cases when creating it:

  • Ensure the password is not empty

  • Hash the given value

I'm unsure of the best approach to achieve this. Here's the code snippet showcasing the problem:

export class UserPassword {
  private readonly value:string

  private constructor(value: string) {
    this.value = value
  }

  public getValue():string {
    return this.value
  }

  // Static factory method where validation should be applied

  static create(password: string):UserPassword {
     // Implementation needed here
  }

  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)
  }
}

Answer №1

Before creating my password object, I conducted some validations to ensure its integrity. It is important to establish validation logic during the object construction process for accuracy. Here is the solution I implemented:

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)
    }
}

Answer №2

Is this what you had in mind? To ensure maximum security, it is recommended to never store the clear value of a password in memory.

// Here is an example of a static factory method that applies validation on user passwords

  static async create(password: string): UserPassword {
      if (!password || password.trim().length === 0) {
           throw new Error("Invalid password");
      }
      var hash = await bcrypt.hash(password, 10);
      return new UserPassword(hash);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered a TypeScript error while utilizing the useContext hook in a React application

Initially, I set the value of createContext to an empty object {}. Afterwards, I provided a context with a new value of {username: 'sasuke1'}. However, when I attempt to access the property Context.username, TypeScript raises the following error: ...

Troubleshooting a Node.js problem related to a schema error involving user ID validation

I am new to working with node.js express and I am facing an issue with my registration form. I have implemented a condition to check if the user ID is already in the database, but for some reason, it always shows a validation error message regardless of th ...

Exploring the parent-child relationship of three components within Angular 2

Currently, I am developing a shopping cart using Angular 2. The application consists of two components - one for categories and another for product listings, both included in the main app component as children. However, I'm facing an issue where these ...

Bring together a set of elements within a collection of identical entities that contain corresponding key-value pairs by utilizing JavaScript

Looking at the object below: a = [ {id: 1, comp: 'ans', stat: 'www', value: ['1', '2']}, {id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b']}, {id: 3, comp: 'ans', ...

Using Higher Order Components in React with TypeScript to pass a component as a prop

Exploring the steps outlined in this guide: https://reacttraining.com/react-router/web/example/auth-workflow. Attempting to replicate the code: const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props = ...

What is the best method for converting an Object with 4 properties to an Object with only 3 properties?

I have a pair of objects: The first one is a role object with the following properties: Role { roleId: string; name: string; description: string; isModerator: string; } role = { roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1", ...

The iPhone/Android devices will not bypass the wifi landing page that has been set up using DNS

Currently, I am in the process of setting up a splash page/ wifi landing page for my public wifi network. I am utilizing a DNS method as outlined in Wikipedia, in which a custom DNS server is hosted to redirect all DNS lookups to a local address with a web ...

Encountering a `Syntax Error` in a Jade view

I am attempting to create a basic chat application using the simple jade view engine with express. Upon running my app, I encountered a syntax error in the following view code, even though it seems quite straightforward. extends layout block scrip ...

Transitioning from Python to NodeJS

Throughout my years of coding in Python, I have relied on this invaluable code snippet: payload = {'grant_type': "password", 'username': "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

The functionality of ui-router appears to be limited when accessed from a nodejs directory, however, it functions properly on

It's strange that ui-router is not functioning as expected on my computer. The setup involves an index.html file serving as a header and test.html as an attached view. Interestingly, it works perfectly fine on Plunker. The content of index.html match ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

Can the return value of a function be directly used as the variable type?

Imagine having the following function: let getData = () => { return { name: 'John', age: 2, isAsian: true } } Is there a way to specify a variable's type as the return type of getData, without assigning i ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

How can I receive live notifications for a document as soon as it is created?

My Angular app is connected to Cloud Firestore, and I've created a function in a service to retrieve a user's rating from the 'ratings' collection. Each rating is stored in this collection with the document ID being a combination of the ...

Can you pass a generic type as a parameter for another generic in Java?

Simply provide a generic type like a callback: type FUNC<ARG,RET, F> = (arg: ARG) => F<RET>; type PROMISE<T> = Promise<T>; type IDENT<T> = T; type A = FUNC<number, void, IDENT>; type A_PROMISE = FUNC<number, void, ...

How to attach an event listener to an input element using Angular

I am looking to add a listener to an input element that will be triggered every time the user changes the input values. The goal is to display the current values chosen by the user. Example HTML template: <div id="idDoseLabel1" class="da ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

Using react-router and expressJS for client-side routing is limited to only a single level deep

I have been trying to implement client-side routing using react-router, but I am facing an issue where the routing behaves as expected only up to one level deep past "/". For example, localhost:8080/ and localhost:8080/{id} work fine, but localhost:8080/vo ...

Obtaining data via a URL and then displaying it in HTML with node.js and express.js

I am currently working on a JavaScript file where I am utilizing Node's 'request' module to make API calls, process data, and return an HTML response to the user. If you're interested, you can take a look at this snippet from my file. ...