Enhancing validation in Express with custom Typescript types for validation in Express Validator

I encountered an error while using the custom method of the express validator

Issue: 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 at least 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,
);

Answer №1

When you use User.findOne in your implementation, it is returning a Promise which is why you need to use Promise.reject to throw an error if necessary. Therefore, you should also return a Promise Object when validation is successful.

if (userDoc) {
    return Promise.reject('User Name is already taken');
}
return Promise.resolve()

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

Guide to retrieving specific information from a JSON file in an Angular application

Struggling with handling this JSON file [ [ { "category": "Bags", "productData": [ { "id": 1000, "name": "Tro ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

Encountering a redirect error during the process of placing a call on hold to set

Here is my current process. When a call comes in, it gets placed into a queue. Once an agent is available, they initiate a connection by calling connect from the client-side Javascript application. The response acknowledges that an agent is attempting to ...

Can property overloading be achieved?

Can functions be overloaded in the same way properties can? I'm interested in overloading properties to have separate documentation for different types passed to them. Currently, both values are set to the same value but I need distinct JSDoc for dif ...

Using TypeScript to define values with the placeholder "%s" while inputting an object as a parameter

One common way to decorate strings is by using placeholders: let name = "Bob"; console.log("Hello, %s.", name) // => Outputs: "Hello, Bob." I'm curious if there's a way to access specific values within an object being passed in without specif ...

What is the best approach to perform type checking on a function that yields varying types depending on the values of its

Currently, I am facing a challenge with a function that takes an argument and returns a different type of value depending on the argument's value. For instance: function foo(arg: 'a' | 'b') { if (arg === 'a') { ret ...

Set a value to the field name within a variable in TypeScript

Can anyone help me with this problem? type A { f1: string; f2; string; } I have a variable that holds the name of a field: let fieldName: string = "f2"; I want to create an object using the fieldName: {"content of fieldName": "sdf"} Any suggestio ...

Guide to configuring the active Tab in Angular 6 using Angular Material Design

I've searched high and low for a solution to this issue, but I haven't been able to find one. In a particular component, I have a material tab control. However, the active tab doesn't display until I click on one of the tabs on the page. a ...

Exploring the combination of Express.js and Jquery UI for enhanced web

I have been developing a node-backbone application where I generate dynamic content and apply jquery UI draggable to the elements I create. However, upon rendering the template system, these elements refuse to budge. The paths seem correct, and I use a cla ...

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call. The first API call fetches something like this: [0 ...

The parameter type '(req: Request, res: Response, next: NextFunction) => void' does not match the type of 'Application<Record<string, any>>'

I'm currently working on an Express project that utilizes TypeScript. I have set up controllers, routers, and implemented a method that encapsulates my controller logic within an error handler. While working in my router.ts file, I encountered an err ...

Navigating through the directories in PUG using the absolute path

Referring to the docs for PUG (), it states: If a path is absolute (example: include /root.pug), it gets resolved by prepending options.basedir. Otherwise, paths are resolved in relation to the file being compiled. To clarify, I understand that this in ...

Does the CORS error pertain only to the nginx server, or do I need to make changes to my code as

After successfully deploying my website for the first time, I encountered an issue with data not being properly sent from the contact form to our node.js server and then to our email address via nodemailer. The error message "Access to XMLHttpRequest at &a ...

Unexpected CORS Error 0 in Nest JS on Android browsers, while functioning properly on PC browsers

I am currently using NestJs as my backend server and Angular as the frontend. Everything works fine when I use Chrome on my computer for making requests, but I encounter an error when using Chrome on my Android device with DevTools enabled. The error mess ...

Unusual Interactions between Angular and X3D Technologies

There is an unusual behavior in the x3d element inserted into an Angular (version 4) component that I have observed. The structure of my Angular project is as follows: x3d_and_angular/ app/ home/ home.component.css hom ...

Collaborate on Typescript Interfaces within a Firebase development environment

I've been developing a Firebase project using Angular for the frontend, and incorporating the @angular/fire library. Within this project, I have created multiple interfaces that utilize firebase and firestore types. For example: export interface ...

Uploading data using NodeJS and EJS

Currently, I am utilizing NodeJS/Express and EJS to develop a form for an API route. However, when attempting a POST request and accessing req.body.password & req.body.confirm, I consistently receive "undefined" as the response. index.js import http from ...

Animation on React child component disappears when re-rendered

My React application utilizes Material UI with a component (let's call it DateSelector) as shown below, slightly altered for demonstration purposes. https://i.sstatic.net/RlPZa.gif Material UI provides animations for clicks and interactions within i ...

Managing HTTP requests with errors within a forEach loop in Angular 9

I am currently coding a script that iterates through an array to make HTTP requests. Most of these requests are directed towards non-existent resources, but I do not have information on which ones specifically. Here is the code snippet I am using: ...