Custom Getter and Setter Methods
In this lesson, you will learn how to encapsulate data processing logic directly within your ORM model definitions using custom getters and setters to transform data automatically as it moves between your application and the database.
Why Use Custom Methods?
Sometimes, the way we store data in a database isn’t the most convenient format for our application code to use. For example, you might store a user's full name as a single string in the database, but your application logic frequently needs to work with the first and last names separately. Instead of manually parsing this string every time you fetch or save a user, you can define a Getter (to format data on retrieval) and a Setter (to process data before it is saved).
Practical Illustration
Imagine an Order model where you store a total amount in cents (to avoid floating-point math issues). You can define a getter to present it as dollars and a setter to ensure any input is converted back to cents:
const Order = sequelize.define('Order', {
totalCents: {
type: DataTypes.INTEGER,
get() {
// Return the value formatted for the application
return this.getDataValue('totalCents') / 100;
},
set(value) {
// Process the value before storing it in the database
this.setDataValue('totalCents', value * 100);
}
}
});
When you access order.totalCents in your code, the getter automatically divides the value by 100. When you assign order.totalCents = 50.00, the setter multiplies it by 100 before the ORM sends the INSERT or UPDATE query to your database.
By shifting this logic into the model, you prevent "leaky abstractions" where your business controllers are forced to know about how the database stores its integers. This keeps your code cleaner, prevents errors, and ensures that data transformation rules are applied consistently throughout your entire application.
Key Takeaway: Use custom getters and setters to maintain a clean interface between your application’s logic and the raw data stored in your database schema.