Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
Validate nodejs model using classes

I am trying to create a model for NodeJS application using JavaScript and MySQL. Now, I got a tip to use the builder pattern because my object becomes too big and is not readable. Therefore I created another class and inside the constructor I created an instance of the basic class, like I saw it in the tutorials.

// Basic
class User {
    constructor(fname) {
        this.fname      = fname;
    };    
}

// Builder for the user class
module.exports = class UserBuilder {
    constructor(fname) {
        this.user = new User(fname);
    }

    setLname(lname) {
        this.user.lname = lname;
        return this;
    }

    setEmail(email) {
        this.user.email = email;
        return this;
    }

    setPassword(password) {
        this.user.password = password;
        return this;
    }

    setAge(age) {
        this.user.age = age;
        return this;
    }

    setGender(gender) {
        this.user.gender = gender;
        return this;
    }

    setAvatar(avatar) {
        this.user.avatar = avatar;
        return this;
    }

    setPhoneNumber(number) {
        this.user.number = number;
        return this;
    }

    build() {
        return this.user;
    }
}

My first question is: how can I validate all the arguments? some of the arguments are not required and the isAdmin should be default False.

To check this, I created a basic instance to see how is build.

const user = require('./models/user.js');
const User = new user('bob').setAge(22).build();
console.log(User); 

My second question is how can I create a method inside the class to edit or delete the object and interact with the database. Or it should be in the controllers?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I probably failed to understand you in some parts of you question. But I tried. So this basically made the builder class a lot smaller with adding newer properties. Now you just need to provide the key & value to add something to object instead of calling a separate method for it.

Note - edit and remove method doesn't need to call build method to return the base user class. All of your questions have been answered in the code comments.

/// Basic
class User {
  constructor(fname) {
    this._validate(fname);
    this.fname = fname;
  }

  _validate(param) {
    //what ever you wanna check before adding into object
  }
}

// Builder for the user class
class UserBuilder {
  constructor(fname) {
    this.user = new User(fname);
  }

  addSomething(key, value) {
    if (typeof key !== "string") {
      //throw "Key provided is not a string."
    }
    key = key.toLowerCase();
    if (key == "role") {
      this.user[key] = this.isAdmin();
      return this;
    }

    this.user[key] = value;
    return this;
  }

  isAdmin() {
    // your way to check if its admin.
    /**
     * if(admin == true) {
     *   return true;
     *  } else return false;
     */
  }

  edit(param, val) {
    if (!this.has(param)) {
      //throw
    } else {
      this.user[param] = val;
      //db operation to edit it.
    }
    return this.user;
  }

  /**
   * By delete Object I suppose delete a property.
   */
  remove(param) {
    if (!this.has(param)) {
      //throw
    } else {
      delete this.user[param];
      //db operation to remove it.
    }
    return this.user;
  }

  has(val) {
    return this.user[val] ? true : false;
  }

  build() {
    return this.user;
  }
};

const userr = new UserBuilder("Vox");
console.log(userr.addSomething("age", 19).build());
console.log(userr.edit("age", 21));
console.log(userr.remove("age"));

This is what the code logged.

User { fname: 'Vox', age: 19 }
User { fname: 'Vox', age: 21 }
User { fname: 'Vox' }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda