Usage of Sequelize transaction
You might remark this line, if (!options.transaction) throw new Error('Missing transaction.');
, in the hashPassword
method decorated with the @BeforeCreate
. As said before, Sequelize provides a strong support of the transaction. So for each action or process of action, you can use a transaction. To use the Sequelize transaction, take a look at the
following example of a UserService
.
@
Injectable
()
export
class
UserService
implements
IUserService
{
constructor
(
@
Inject
(
'UserRepository'
)
private
readonly
UserRepository
:typeof
User
,
@
Inject
(
'SequelizeInstance'
)
private
readonly
sequelizeInstance
)
{
}
...
}
We have injected both the model and the Sequelize instance that we talked about earlier in this chapter.
To use a transaction to wrap some access to the database, you can do the following:
public
async
create
(
user
:IUser
)
:
Promise
<
User
>
{
return
await
this
.
sequelizeInstance
.
transaction
(
async...