I have an application in NestJS, when a request is made to create an object, it validates that an object with the same name and some other parameters does not exist, in those validations the process takes approximately 30 seconds, before actually being saved.
But when from the angular front several requests are made by pressing the “create” button many times, and the process of the first one has not been completed, all the requests pass because the name does not yet exist for the system since the object is not yet saved with this name. In the end the objects end up being saved duplicates.
I know it can be avoided by disabling the “create” button from front until a response is obtained.
But my task from the back is to also prevent this error, I can think of a set.timeout in receiving the request, but I am not sure, more than anything, only allow a request every “x” time only for each user.
Any idea, I have something like this extract on my code:
async createRole(role: RoleDto, permissions) {
const { Name, Account } = role;
if (!Name)
throw new UnprocessableEntityException(
'The Name must be provided.',
);
if (!Account)
throw new UnprocessableEntityException(
'The Account must be provided.',
);
const roleExist = await this.rolesRepository.findOne({
where: { Name, Account },
});
if (roleExist)
throw new ConflictException(
'Name has been already used on this corporation.',
);
var roleToSave = new Role();
roleToSave.Name = Name;
roleToSave.Account = Account;
roleToSave = await this.rolesRepository.save(roleToSave);