What is the method for incorporating an async middleware into a router route?

I am currently setting up routes for an express router in my project. I have a validator that deals with promises, requiring me to use await in the code. Here is how it looks:

constructor() {
    this.router = express.Router();
    this.router.use(express.json());
    this.router.use(express.text({ type: ['text/plain', 'text/html'] }));
  }

  async addCreateTaskRoute(validator, handler) {
    if (!handler) {
      throw Error('cannot add empty handler');
    }

    this.router.post('/tasks', await validator, handler);

    return this;
  }

Do you think this solution is appropriate? Are there any alternatives? The context of this coding snippet is within a middleware of the project, where the validator and handlers are sourced from external modules and are of type express RequestHandler.

Answer №1

It is important that your validator functions asynchronously call the next() function upon successful validation. This will trigger the next middleware in line, which is the handler. In case of unsuccessful validation, an error is generated and next() is not invoked, halting any further processing by other middlewares.

async function validator(req, res, next) {
  var result = await performValidation(...);
  if (result) {
    next();
  } else {
    res.status(400).end("Error message");
  }
}
this.router.post("/tasks", validator, handler);

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

How can I transmit information to the model without relying on query string parameters in Express?

Currently, I am working with two controllers - authController and onboardingController. The authController communicates with the onboardingController using the following line of code: res.redirect('/onboarding/info?profileId=' + profile.id + &ap ...

Please ensure that the form is only submitted when at least one checkbox is selected by utilizing JavaScript

When I visit the following form: Upon filling out the details and clicking submit, if I forget to check a checkbox, a prompt appears stating "please select any one checkbox" with an 'ok' button. After clicking 'ok', the form is then su ...

Create a form with Vue that generates input fields based on JSON data and

I am seeking assistance with implementing a truncate filter for vueformulate in my project. I am generating the form from json data and need to limit the label to 80 characters, with a read more/less option. The data is dynamic, so changing the label in th ...

The JavaScript exec() RegExp method retrieves a single item

Possible Duplicate: Question about regex exec returning only the first match "x1y2z3".replace(/[0-9]/g,"a") This code snippet returns "xayaza" as expected. /[0-9]/g.exec("x1y2z3") However, it only returns an array containing one item: ["1"]. S ...

Encountering an issue while attempting to extract an ACF field in WordPress using JavaScript

When I write the following code, everything works fine: <script> $(document).ready(function(){ var user_id = '<?php echo get_current_user_id(); ?>'; // This is working var subject = "<?php echo the_field('subject ...

Discovering common elements in various arrays of objects

Details: record1 = [{"site": "The Blue Tiger", "zipcode": "E1 6QE"}, {"site": "Cafe Deluxe", "zipcode": "E6 5FD"}] record2 = [{"site": "Blue Tiger", "zi ...

Using JavaScript or TypeScript to locate the key and add the value to an array

My dilemma involves an object structured as follows: [{ Date: 01/11/2022, Questionnaire: [ {Title: 'Rating', Ans: '5' }, {Title: 'Comment', Ans: 'Awesome' } ] }, { Date: 01/11/2022, Questionnaire ...

Trouble rotating camera in THREE.JS?

How can I adjust my camera to look behind, with the center of the pong table being at x=0,z=0? I've tried changing the camera.lookAt settings but haven't had success. You can see the current camera view here. scene = new THREE.Scene(); scene ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

The NgFor is unable to iterate over an array because it is being treated as an

When attempting to call a new endpoint for displaying data, I noticed that the previous set of data is wrapped with an extra pair of brackets '[]', which seems to be causing a problem. The new endpoint does not format the data in this way when I ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

Attempting to use Model.remove() is proving to be completely ineffective

Currently, I am utilizing expressjs (version 3.10.10), mongoose (version 3.10.10), and mLab for my project. Below is the code snippet: app.get("/deleteDevice/:query", function(req, res) { var query = req.params.query; query = JSON.stringify(quer ...

Leverage JSON data from an API within JavaScript, sourced and accessed through PHP

I'm seeking advice on using JSON data (loaded in PHP) with JavaScript. I am currently retrieving the JSON from an API, but someone suggested that using curl would be more efficient? I've attempted to research curl, but haven't found exactly ...

Mesh is making an excessive number of draw calls

After importing some mesh from Blender using the three.js exporter from the utils folder, I noticed that it only has 3 materials but is utilizing 28 draw calls. Why is this happening? I expected it to use only 3 draw calls. View mesh image ...

Focus on a particular div in order to enable scrolling beyond its boundaries

Whenever I move my mouse over the div tag, I am able to scroll the content. However, if I move the mouse outside of the div box, scrolling stops. Is there a way to make the specific div element track the mouse pointer no matter where it goes? <div st ...

What is the most effective approach to generating user accounts (email + password) using MongoDB and express?

As I develop my app, I'm curious about the most effective methodologies and packages that people use for creating user accounts in SaaS applications. I have been considering using Express, MongoDB, and JWT - but is this approach the best system? What ...

Encountering problem with image file encoding while using res.download in Express.js

My node.js server with expressjs is set up for local development, where I store and retrieve various files through basic HTTP calls. Most of the time, everything works smoothly. However, on rare occasions, a small number of files return to the end-user sig ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

Sequelize generates vague error messages during database queries

Sequelize version: 6.13.0 Database version: PostgreSQL 13.3 In my experience with Sequelize, I've noticed that when there is an issue with a query, it does not provide clear error messages. Unlike this example on Stack Overflow where an error about a ...