'How does this function that takes in a RequestHandler in express work?
I was browsing through some code examples for Express server on GitHub and came across this function used to wrap around REST API controllers and was confused how it works...
import { RequestHandler } from 'express';
export const catchErrors = (requestHandler: RequestHandler): RequestHandler => {
return async (req, res, next): Promise<any> => {
try {
console.log(req.body) **// returns requestHandler's req parameter //**
return await requestHandler(req, res, next);
} catch (error) {
next(error);
}
};
};
It is used to wrap around REST API controllers to catch errors and pass it into an error handling middleware. A brief example of such usage would be this:
import {catchErrors} from './error'
export const fetchData = catchErrors(async (req: Request, res: Response) => {
/// perform data fetching here ///
return res.status(200).send()
})
I am confused as to how the catchErrors function works. To my understanding, requestHandler parameter refers to the original REST controller callback. However, the next part of catchError where it says
return async (req, res, next): Promise<any> => {...}
Where does this (req, res, next) come from? I tried console logging the req.body
and it turned out to be the request body of the requestHandler parameter parsed above. I do not understand how the requestHandler's (req, res, next) can be referenced in this way instead of say requestHandler.req (which does not work)?
GitHub link where I found this code: https://github.com/oldboyxx/jira_clone/blob/master/api/src/errors/asyncCatch.ts
Solution 1:[1]
catchErrors
is just a helper function to return a middleware function from another middleware function, enhancing or adding features. in your case, think of fetchData
as
async (req, res, next): Promise<any> => {
try {
console.log(req.body) **// returns requestHandler's req parameter //**
const fetchFunction = async (req: Request, res: Response) => {
/// perform data fetching here ///
return res.status(200).send()
}
return await fetchFunction(req, res, next);
} catch (error) {
next(error);
}
};
which is a valid middleware for express. take a look at higher order function, decorator pattern and closures which are the same concept.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |