Sequelize allows you to set up custom getters and setters which make querying and setting data a lot easier and more efficient. For example, it is possible that the data you are storing in the database is lowercase. If you want the user to see the data in uppercase, then you may use Sequelize getters. Also, let’s say you want to save the password of a user in a database. You may already know that storing passwords directly in the database is not a good practice, so before storing the passwords we can encrypt them using setters.
Refer to one of my previous articles to set up your project here.
Today we will work with the user’s model. Right now my folder structure looks like this.
Now you will see a user.js file in the models folder, create this file in your model’s folder as well. We will define the user model in the following way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define("User", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
return User;
};
Here our user has a self-incrementing ID, a username that has to be unique, and a password.
If you run this then you will see the following query getting executed in the terminal.
This is the SQL query to create a users table. In the MySQL workbench you can see the following table.
First, let’s create an API to store some data in our database. Type the following code in your index.js file.
1 2 3 4 5 6 7 8 9
app.post('/', async (req, res) => { const data = req.body; try { await db.User.bulkCreate(data); res.send('data added'); } catch (err) { res.send(err.message) } })
Here I have used the bulkCreate() function instead of create() to populate the database faster. We will send an array of json objects which contain our data.
Make a post request to the address / for your localhost with the following data.
1 2 3 4 5 6 7 8 9 10
[ { "username": "srajan123", "password": "devPassword" }, { "username": "srajan456", "password": "test123" } ]
Now when you hit send the data will be stored in the database like this.
Let’s write our first getter.
To write a getter we use get() function and it is written inside the model itself. We will first write a getter to retrieve the usernames in uppercase. To do this, modify the username key in the model like this.
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
get() {
const rawValue = this.getDataValue(‘username’);
return rawValue ? rawValue.toUpperCase() : null;
}
},
Now we will create an API that will fetch the data of a user whose ID we send. Write the following API in index.js file.
1 2 3 4 5 6 7 8 9 10 11 12 13
app.get('/:id', async (req, res) => { const id = req.params.id; try { const user = await db.User.findOne({ where: { id } }); res.send(user.username); } catch (err) { res.send(err.message); } })
Now let’s see if this works. Make a get request to this address /:id for your localhost and pass the value 1 in postman’s ID variable. Now when we run this, we will be able to see that the output is indeed in uppercase, even though we can clearly see that it is in lowercase in our database.
Let’s now have a look at setters. We use the set() function to write our setters. We will hash our password before storing it in our database. Here we will not use any third party library to hash but just a function that reverses the string. First create the following hash function in user.js. Please note that this does not even remotely resemble how hashing is done in real life.
1
2
3
4
5
const hash = (str) => {
return str.split("")
.reverse()
.join("");
}
Now modify the password field of the user model like below…
1 2 3 4 5 6 7
password: { type: DataTypes.STRING, allowNull: false, set(value) { this.setDataValue('password', hash(value)); } },
Now again save some data in the database using the POST API. Let’s say we send the following data.
1 2 3 4 5 6
[ { "username": "srajanRev", "password": "devPassword" } ]
We will get the following result in the database.
As you can see the password is reversed.
Thanks for reading about getters and setters in Sequelize.