question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Problems with async await in registerAsync

See original GitHub issue

Environment info

Validatorjs version: 3.22.1 Node.js version: v12.18.3

Problem

I need the same functionality of issue #345, I want check in my database if the new value is unique, but the validation is not working as it should.

Implementation - Register Async

const Validator = require('validatorjs');
const services = require('../../index');
const NotFoundError = require('../errors/http-error');

Validator.registerAsync('unique', async (value, requirement, param, passes) => {
  if (typeof requirement !== 'string') {
    throw new Error('Invalid unique rule, you must enter the table!');
  }

  const args = requirement.split(',');

  const entityName = args[0];
  const field = args[1] || 'id';

  if (Object.keys(services).includes(entityName) === false) {
    throw new Error(`The entity ${entityName} doesn't exist.`);
  }

  const filters = {};
  filters[field] = value;

  /** @var {object} repository */
  const repository = services[entityName];

  try {
    await repository.getFirst(filters);
  } catch (error) {
    if (error instanceof NotFoundError) {
      passes(false, `The ${param} is already registered.`);
    }

    throw error;
  }

  await passes(true);
  return true;
});

module.exports = Validator;

Implementation - Validation

const Validator = require('../../lib/validatorjs'); // Import previous code 

const data = {
  name: 'Name',
  email: 'non-unique@email.com',
  password: 'password',
};

const rules = {
  name: 'required',
  email: 'required|unique:users,email',
  password: 'required',
};

const validation = new Validator(data, rules);

const passes = () => {};

const fails = () => {
  const message = JSON.stringify(validation.errors.all());
  throw new UserInputError(message);
};

await validation.checkAsync(passes, fails);

Expected behaviour

Wait for await validation.checkAsync(passes, fails); and throw an exception.

Current behavior

The code below is taken from Implementation - Register Async

passes(false, `The ${param} is already registered.`);`

When the logic of the code does not go through the above section everything happens as it should.

When the code logic goes through the above section, the code does not respect the await validation.checkAsync(passes, fails); and the exception is returned asynchronously, breaking the application logic.

When this snippet is inserted before the line with await, the code behaves as expected.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:11 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
feeh27commented, Mar 29, 2021

I am very grateful for the feedback, as I said earlier, I am willing to contribute, however, as I still do not understand the operation of registerAsync and checkAsync I do not know where to start.

If you show me the way (when possible), I can contribute to the solution.

1reaction
wulfsoltercommented, Sep 1, 2022

Cleaning up the approach that @feeh27 did a little bit, this is what I’m using:

    const validation = new Validator(data, rules, customErrorMessages);
    const validatorPromise = new Promise((resolve) => { validation.checkAsync(() => { resolve(true); }, () => { resolve(false); }); });
    const result = await validatorPromise;

    // failed validation
    if (result === false) {
      const allErrors = validation.errors.all();
      ...
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to import a registerAsync in a dynamic Nestjs module?
registerAsync however, I'm having trouble figuring out what to do. Any help is much appreciated :) import { Module, DynamicModule, Provider, ...
Read more >
Async providers | NestJS - A progressive Node.js framework
The syntax for this is to use async/await with the useFactory syntax. The factory returns a Promise , and the factory function can...
Read more >
Using Asynchronous Methods in ASP.NET 4.5 - Microsoft Learn
The await keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code.
Read more >
Is there a way to define a function that can be used as a nomal ...
Instead of writing: async def f(): [some code] await some_coro() … ... the problem that a function that was normal had to become...
Read more >
How to register an async Task event hander for the Messenger
The problem is that using the async void method means the method is not testable as it cannot be awaited. What's the best...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found