Advanced TypeORM
Let’s take a look at security.
Security first
If you went through the Sequelize chapter in this same book, you might be familiar with the concept of lifecycle hooks. In that chapter, we are using a beforeCreate
hook to encrypt the users’ passwords before we save them to our database.
In case you’re wondering if such a thing exists also in TypeORM, the answer is yes! Though the TypeORM documentation refers to them as “listeners” instead.
So, to demonstrate its functionality, let’s write a very simple User
entity with a username and a password, and we will make sure to encrypt the password before we save it to the database. The specific listener we will be using is called beforeInsert
in TypeORM.
@
Entity
export
class
User
{
@
PrimaryGeneratedColumn
(
'uuid'
)
id
:string
;
@
Column
()
username
:string
;
@
Column
()
password
:string
;
@
BeforeInsert
()
encryptPassword() {
this
.
password
=
crypto
.
createHmac
(
'sha256...