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,
);

1 Answers

1
dimitris tseggenes On Best Solutions

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()