Having difficulty with utilizing array.every() properly, leading to inaccurate results

Struggling to validate an array of IDs using a custom validator in a nestjs project. The issue arises when passing the array of IDs to a service class for database querying, as the validation always returns true even with incorrect IDs.

Snippet of the custom validator function:

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, registerDecorator, ValidationOptions } from "class-validator";
import { DeviceService } from "../device/device.service";
import { Injectable } from "@nestjs/common";

@ValidatorConstraint({ async: true })
@Injectable()
export class DevicesArrayValidatorConstraint implements ValidatorConstraintInterface {

    constructor(private deviceService: DeviceService) { }

    async validate(devices: Array<number>, args: ValidationArguments) {
        let result = devices.every(async (deviceId) => await this.deviceService.validateDevice(deviceId));
        if(result){
            return true;
        }
        else{
            return false;
        }
    }

    defaultMessage(args: ValidationArguments) { 
        return "Error message here";
    }

}

export function ValidDevices(validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            validator: DevicesArrayValidatorConstraint
        });
    };
}

Segment from Service Class function:

async validateDevice(deviceId: number) {
  try {
    let result = await this.deviceRepository.findOneOrFail(deviceId)
    if(result){
      console.log(`Inside try block, ID: ${  deviceId}`)
    }
  } catch (error) {
    return false;
  }
  return true;
}

When passing an array of devices: [1,4], where 1 is valid and 4 is invalid, there seems to be a double boolean result upon logging.

Console message demonstration attached below

Answer №1

every doesn't fully grasp the concept of async functions. It only interprets the promise returned as a truthy value.

You have a couple of choices to tackle this:

If you prefer validating all devices simultaneously and then checking the result:

const validityFlags = await Promise.all(devices.map(deviceId => this.deviceService.validateDevice(deviceId)));
let result = validityFlags.every(Boolean);

Alternatively, if you want to validate each device one by one in order, skipping later ones once an invalid one is found:

let result = true;
for (const deviceId of devices) {
    const valid = await this.deviceService.validateDevice(deviceId);
    if (!valid) {
        result = false;
        break;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dividing an AngularJS module across multiple iFrames on a single webpage

Currently, I am working on a web application that consists of 1 module, 5 pages, and 5 controllers. Each HTML page declares the same ng-app. These pages are loaded within widgets on a web portal, meaning each page is loaded within an iFrame in the portal. ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

Having trouble running classes using Maven test with the Testng.xml file in the terminal, however, it runs smoothly in Eclipse

While I have been successful in running my solution through the testng suit in the Eclipse console, I am facing difficulties executing the testng.xml file via Maven integrated with Sauce Labs in the terminal. Output received on the terminal: ------------ ...

Tips for properly implementing a bcrypt comparison within a promise?

Previously, my code was functioning correctly. However, it now seems to be broken for some unknown reason. I am using MariaDB as my database and attempting to compare passwords. Unfortunately, I keep encountering an error that says "Unexpected Identifier o ...

How can I resolve the Vue warning about an unknown custom element <password-input>?

I've been working on resolving an error within a component, but unfortunately, I'm still encountering issues. The error message is as follows: [Vue warn]: Unknown custom element: - have you registered the component correctly? For recursive co ...

Make sure link opens in the same window/tab

Currently, I am utilizing the Open Link in Same Tab extension on Google Chrome. This extension can be found here. The purpose of this extension is to ensure that all links open in the same window/tab, which is necessary for touch screen kiosk left/right s ...

Function executed many times during click action

I have developed a web application that allows users to input any keyword or statement and receive twenty results from Wikipedia using the Wikipedia API. The AJAX functionality is working perfectly. The app should dynamically create a DIV to display each r ...

Setting a default date dynamically for v-date-picker in the parent component, and then retrieving the updated date from the child component

I'm working with a custom component that utilizes the v-date-picker in various instances. My goal is to have the ability to dynamically set the initial date from the parent component, while also allowing the date to be modified from the child componen ...

"Enhancing User Experience with Multiple Conditional Checkboxes in jQuery

Having difficulty making a checkbox change some HTML content using JQuery. There is a standard html checkbox with the following attributes <input type="checkbox" name="AQN1" class="checkbox Q1" value="AQN10" id="3mcq"> <input type="checkbox" nam ...

changing the validation function from using if statements to utilizing switch statements

Currently, I am refactoring a form in react and planning to offload most of the state and logic to the parent component. This decision is made because the parent's state will be updated based on the form submission results. However, I encountered an i ...

Can a single button click be shared across multiple forms?

The main concept involves a grid where when a user double-clicks on a row, a modal window (Bootstrap panel) opens with a panel-body section for editing the data and a panel-footer containing a btn-group for actions like "Save", "Cancel", or "Close". This s ...

"Converting a basic function into a promise for an AngularJS tutorial: How to handle the error message '

To help my colleagues understand AngularJS, I am creating a dummy exercise. In this example, I want to call a service that provides an Object Array to be passed into a Controller and assigned to a $scope variable (using information about the Beatles). Inst ...

Connect a function to create a new document element in order to modify the

I am attempting to intercept document.createElement in order to modify the value of the src property for each assignment. My current approach involves: var original = document.createElement; document.createElement = function (tag) { var element ...

Concentrate on Selecting Multiple Cells in ag-Grid (Similar to Excel's Click and Drag Feature)

Is there a way to click and drag the mouse to adjust the size of the focus box around specific cells in ag-Grid? This feature is very handy in Excel and I was wondering if it is available in ag-Grid or if there is a workaround. Any insights would be apprec ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Unable to display information retrieved from an API within a React application

I am facing an issue with rendering questions fetched from an API. I have set up the state and used useEffect to make the API call. However, when I try to display the questions, it seems to disrupt my CSS and show a blank page. I even attempted moving the ...

How can you notice when a DOM element is deleted from the page?

I am in the process of creating a custom directive that will ensure only one element is active at a time. Directive: displayOneAtATime Description: This directive can be applied to a DOM node to guarantee that only one element with this directive can be v ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...