开始一个 Transaction ,然后去做一些数据处理,如果正常就 Commit 这个 Transaction,如果处理数据出了问题就 Rollback。
async execute(command: InviteRegisterCommand) {
const {
params: { invite, user },
} = command;
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
// 开始 Transaction
await queryRunner.startTransaction();
try {
// 创建用户
const userEntity = await queryRunner.manager.save(UserEntity, user);
// 找出角色
const roles = await queryRunner.manager.find(RoleEntity, {
name: In([Role.Authenticated, Role.Member]),
});
// 保存用户角色
const userRoles = roles.map((role) => {
return { roleId: role.id, userId: userEntity.id };
});
await queryRunner.manager.save(UserRoleEntity, userRoles);
// 创建 Pass
if (invite.trailId) {
await queryRunner.manager.save(PassEntity, {
trailId: invite.trailId,
userId: userEntity.id,
});
}
// 更新 Invite
invite.userId = userEntity.id;
await queryRunner.manager.save(InviteEntity, invite);
// 删除 Invite
await queryRunner.manager.softDelete(InviteEntity, invite.id);
// Commit Transaction
await queryRunner.commitTransaction();
} catch (error) {
// since we have errors lets rollback the changes we made
await queryRunner.rollbackTransaction();
} finally {
// you need to release a queryRunner which was manually instantiated
await queryRunner.release();
}
return command;
}