2

When using the custom method of express validator I'm getting error

Argument of type '(userDoc: User | null) => Promise<never> | undefined' is not assignable to parameter of type '(value: User | null) => PromiseLike<never>'.
  Type 'Promise<never> | undefined' is not assignable to type 'PromiseLike<never>'.
    Type 'undefined' is not assignable to type 'PromiseLike<never>'.

import express from 'express';
import { body } from 'express-validator/check'
import User from '../models/User';

import { login, signUp } from '../controllers/auth';
const router = express.Router();

router.post(
  '/sign-up',
  [
    body('username', 'User Name should be atlest 4 characters long')
      .isLength({ min: 4 })
      .isString()
      .trim()
    .custom((username: string, { req }) => {
      return User.findOne({ username }).then(userDoc => {
        if (userDoc) {
          return Promise.reject('User Name is already taken');
        }
      });
    })
  ],
  signUp,
);

3
  • There is nothing wrong with this piece of code. Please post more details on the context where you call body(). Commented Apr 20, 2019 at 12:09
  • Try return Promise.resolve() right after if conditional, In case there is no User found, you should return A Promise Object. Commented Apr 20, 2019 at 12:26
  • it worked, but can you explain why? Commented Apr 20, 2019 at 12:29

1 Answer 1

1

The way you implement User.findOne returns a Promise. That's why you use Promise.reject in order to throw an error. So you have to return a Promise Object too in case validation is successful.

if (userDoc) {
    return Promise.reject('User Name is already taken');
}
return Promise.resolve()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.