Pregunta

Summary of question: Conceptually, what are getters and setters and why would we use them?

Excerpt from http://docs.sequelizejs.com/en/latest/docs/models-definition/?highlight=getterMethods#getters-setters:

It is possible to define 'object-property' getters and setter functions on your models, these can be used both for 'protecting' properties that map to database fields and for defining 'pseudo' properties.

  1. What does it mean by 'protect'? Against what?

  2. What are 'psuedo' properties?

I'm also struggling with the example code below. We appear to be setting 'title' twice. And what is the argument 'v'?

See below:

var Foo = sequelize.define('Foo', {
  title: {
    type     : Sequelize.STRING,
    allowNull: false,
  }
}, {

  getterMethods   : {
    title       : function()  { /* do your magic here and return something! */ },
    title_slug  : function()  { return slugify(this.title); }
  },

  setterMethods   : {
    title       : function(v) { /* do your magic with the input here! */ },
  }
});

A concrete example instead of "do magic" would be greatly appreciated!

¿Fue útil?

Solución

pseudo properties

Would be properties that, from the perspective of the user seems like regular properties of the object, but do not exist in the database. Take for example a user object that has first names and last name fields. You could then create a fullname setter:

var foo = sequelize.define('foo', {
    ..
}, {
    getterMethods: {
        fullName: function () {
            return this.getDataValue('firstName') + ' ' + this.getDataValue('lastName')
        }
    },
    setterMethods: {
        fullName: function (value) {
            var parts = value.split(' ')

            this.setDataValue('lastName', parts[parts.length-1])
            this.setDataValue('firstName', parts[0]) // this of course does not work if the user has several first names
        }
    }
})

When you have a user object you can simply do

console.log(user.fullName) 

To see the user's full name. The getter is then being invoked behind the scenes.

Similarily, if you define a setter method for full name you could do

user.fullName = 'John Doe'

Which would then split the passed string into two parts and save them in first and last name. (see the simplified example above)

Protect properties

@ahiipsa already provided a good example of this. Getters are called when you do user.toJSON(), so you can use getters to easily remove sensitive data before sending it to the user.

Otros consejos

@Column({
type: DataType.STRING,
set : function (this: User, value: string) {
  this.setDataValue("password", cryptService.hashSync(value));
  }
})
password: string;

This is the snippet which is used to store hashed password in database in 
place of normal string.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top