Custom Joi middleware in Express v4 is failing to pass the Request, Response, and Next objects

I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema.

In the past, I have created middlewares for JWT validation without passing any parameters, and they worked effectively.

Configuring the route and applying the middleware function

app.route('/identity').post([validator(identitySchema)], this.identityController.createIdentity);

The validator middleware function

export const validator = (schema: object) => {
  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    console.log('req: ' + req.body); //prints req: [object Object]
    console.log('schema: ' + schema); //prints schema: [object Object]
    //VALIDATION LOGIC GOES HERE
  };
};

If I had written just

app.route('/identity').post([validator], this.identityController.createIdentity);

export const validator(req: Request, res: Response, next: NextFunction) => {

It would have automatically picked up req, res, etc...

Answer №1

This is my custom Joi validation middleware implementation

Example of how it's used in a route

import express from 'express'
import validateJoi from '../middlewares/validate-joi'
import Joi from '@hapi/joi'

const router = new express.Router()

const schemaExample = Joi.object({
  userId: Joi.number().required(),
  tasks: Joi.array().items(
    Joi.object().keys({
      id: Joi.number().required(),
      description: Joi.string().required()
    })
  ).required()
})

router.post('/', validateJoi(schemaExample), myController.handleUserRequest)


export default router

Custom Joi Validation Middleware

export default (schema) => {
  return (req, res, next) => {
    const { error } = schema.validate(req.body)
    const isValid = error == null
    if (isValid) {
      next()
    } else {
      const { details } = error
      const errorMessages = details.map(i => i.message)
      res.status(422).json({
        status: false,
        error: errorMessages
      })
    }
  }
}

I hope this solution works for you!

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

Encountering an Unexpected Token Error while using Jest in Next.js for node-modules

After setting up my Next.js project, I decided to install jest by running the command below: npm i --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom I then created a jest.config.json file with the following code snipp ...

Displayed in the xmlhttp.responseText are the tags

Why do tags appear when I input xmlhttp.responseText into my textbox? It displays <!DOCTYPE html><html><body></body></html> along with the desired content. Is there a way to prevent the tags from being displayed? Here is the ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Storing data with Laravel 5.3 using Storage::put and XMLHttpRequest

Attempting to send a file using DRAG & DROP with XMLHttpRequest. $images = $_FILES['images']; When I use foreach: foreach($images["name"] as $file => $name) and move_uploaded_file($images["tmp_name"][$file], $images_dir . $name it works ...

What is the process for incorporating a glossiness / specular texture onto a GLTF model?

QUERY: I currently possess a specular/glossiness texture image for a model that has not yet been integrated into the GLTF model. Is there a way to incorporate/add this texture to my model in order to achieve a reflective/glossy appearance where required? ...

Retrieve data from AJAX once the cycle is complete

Currently, I am attempting to calculate the sum of results from an external API by making a single request for each keyword I possess. The code is functioning properly; however, the function returns the value before all the ajax requests are completed. Eve ...

I am experiencing a 404 error when attempting to import a local JS file in Angular

After creating a new project with "ng new xxx", all you need to do is add one line of code in index.html: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Bbb</title> <base href="/&g ...

Stop NodeJs express server from mistakenly loading index instead of another resource

Is there a way to stop the node express server from automatically reloading the index.html file when it cannot find other specified files? As a beginner in node.js, here is how I am starting the server: // Setting up express server http.createServer(app) ...

Tips for creating a custom Angular Material modal window that is fully responsive to its parent modal window

Hey there! I've put together a custom modal window in Angular Material by combining the custom modal window example with the Angular Material slider demo. Everything is working well except for the fact that the sliders inside the modal window are not ...

The use of `super` in Typescript is not returning the expected value

Trying to retrieve the name from the extended class is causing an error: Property 'name' does not exist on type 'Employee'. class Person { #name:string; getName(){ return this.#name; } constructor(name:string){ ...

Null value returned by EJS variable

I am encountering an issue with my node/express/ejs application where the variable appears to have a null value when I visit the page. Below is the route in question: router.get("/events", isLoggedIn, function(req,res){ User.findById(req.params.id).p ...

Tips on improving image loading speed in JavaScript code

I'm working on a simple weather map that changes the background image depending on the current weather status. However, I've noticed that there is a delay in changing the image when the weather status changes. I'm wondering if this delay is ...

Tips for simulating focus on a Material-ui TextField with a button press

My web application features a unique method for indirectly filling in text fields. Since there are multiple clicks involved (specifically in a calendar context) and numerous fields to fill, I want to provide users with a visual indication of which field th ...

Applying CDNJS CSS or external CSS to Nodemailer HTML templates with Jade and Express: A Guide

I am attempting to send emails using node mailer. I have a jade template with HTML markup in an external file, which is compiled and rendered correctly. However, the styles inserted through maxcdn or cdnjs are not being applied. In this situation, how can ...

express req.session returns as undefined in Node.js

I'm really struggling with this issue. Despite everything I read about express session claiming that it should work seamlessly, I can't seem to make it function correctly. Here is my entire app configuration: app.configure -> app.set &apos ...

What is the best method for implementing ajax in Codeigniter?

Exploring the best approach to writing ajax in CodeIgniter. Is it acceptable to write ajax in views, or is it better to create a new directory named assets at the root of the CodeIgniter project folder and relocate all scripts to a js folder within our a ...

Why is it displaying undefined even though there is data stored in Firebase?

I am experiencing an issue where the datatable row is displaying "undefined" instead of the data from my Firebase database. Even when I tried inserting random data into the HTML file for the datatable, it still shows undefined. Here is a link to My Datata ...

Cannot proceed with module import: Type 'ModuleWithProviders<T>' must have a single type argument

ERROR in node_modules/@angular/fire/firestore/firestore.module.d.ts:7:74 - error TS2314: Generic type 'ModuleWithProviders<T>' requires 1 type argument(s). 7 static enablePersistence(persistenceSettings?: PersistenceSettings): ...

Tips for troubleshooting and optimizing the functionality of the authentication controller in Node.js (Express) - Let's make it work seamlessly

As I endeavor to send a verification email using node mailer and send grid when a user signs up, I have incorporated the necessary functions within the User create function. Additionally, I have made some modifications inside the login function to ensure t ...

Can a client receive a response from server actions in Next.js 13?

I'm currently developing a Next.js application and I've created an action in app/actions/create-foo-action.js. In this server action, I am attempting to send a response back to the client. import { connectDB } from "@utils/database" imp ...