0

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);
laur
  • 500
  • 1
  • 9
  • 23
  • Maybe this will give you some insight https://dev.to/marmicode/end-to-end-http-request-cancelation-with-rxjs-nestjs-4gnd I didn't implement this feat but I'm pretty sure rxjs could help you somehow – Micael Levi Dec 14 '21 at 22:37
  • also, what about https://github.com/nestjs/throttler? – Micael Levi Dec 14 '21 at 22:38
  • Throttle is a rate limiting. I suggest two things. First, do your frontend more mistake-proof using libraries such as Rxjs (as Micael has suggested) or XState (my suggestion). Second, the database will thrown an exception if you try to save a repeated data in a primary key or a composite key (if you want to use more than one column as primary key), so you can throw a Bad Request error, here you go an example https://pastebin.com/m3EAHXDr – luisbar Dec 15 '21 at 04:22

0 Answers0