Skip to content
On this page

Accessors & Mutators

Accessors, mutators allow you to transform Sutando attribute values when you retrieve or set them on model instances.

Accessors & Mutators

Defining An Accessor

An accessor transforms an Sutando attribute value when it is accessed. To define an accessor, create a get{Attribute}Attribute method on your model where {Attribute} is the "studly" cased name of the column you wish to access.

In this example, we'll define an accessor for the first_name attribute. The accessor will automatically be called by Sutando when attempting to retrieve the value of the first_name attribute:

js
const { Model } = require('sutando');

class User extends Model {
  getFirstNameAttribute(value) {
    return value.toUpperCase();
  }
}

As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may simply access the first_name attribute on a model instance:

js
const user = await User.query().find(1);
 
const firstName = user.first_name;

You are not limited to interacting with a single attribute within your accessor. You may also use accessors to return new, computed values from existing attributes:

js
getFullNameAttribute() {
  return `${this.first_name} ${this.last_name}`;
}

Defining A Mutator

A mutator transforms an Sutando attribute value when it is set. To define a mutator, define a set{Attribute}Attribute method on your model where {Attribute} is the "studly" cased name of the column you wish to access.

Let's define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

js
const { Model } = require('sutando');

class User extends Model {
  setFirstNameAttribute(value) {
    this.atttributes.first_name = value.toLocalLowerCase();
  }
}

The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Sutando model's internal attributes property. To use our mutator, we only need to set the first_name attribute on an Sutando model:

js
const user = User.query().find(1);

user.first_name = 'Sally';

In this example, the setFirstNameAttribute function will be called with the value Sally. The mutator will then apply the toLocalLowerCase function to the name and set its resulting value in the internal attributes object.

Released under the MIT License. (dev)