Problems with async await in registerAsync
See original GitHub issueEnvironment 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:
- Created 3 years ago
- Reactions:1
- Comments:11 (2 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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
andcheckAsync
I do not know where to start.If you show me the way (when possible), I can contribute to the solution.
Cleaning up the approach that @feeh27 did a little bit, this is what I’m using: