Last active
March 18, 2023 00:01
-
-
Save omarwaleed/bf271dc5ee304810ee2d0821d0c637dc to your computer and use it in GitHub Desktop.
Allows you to wrap your express async handlers in a way that removes the need to put all your function body handlers in a try catch phrase. Instead, if an error is thrown, it returns a default response from the server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Request, Response, NextFunction } from 'express'; | |
type ExpressRouteFn<T> = (req: Request & Partial<T>, res: Response, next: NextFunction) => unknown; | |
export function wrapper<T = {}>(fn: ExpressRouteFn<T>): ExpressRouteFn<T> { | |
return function(req, res, next) { | |
return (fn(req, res, next) as Promise<ExpressRouteFn<T>>).catch((err) => next(err)); | |
} | |
} | |
export function wrapMulter<T = {}>(multerFn: ExpressRouteFn<T>): ExpressRouteFn<T> { | |
return wrapper(async (req, res, next) => { | |
return multerFn(req, res, function(err) { | |
if(err) { | |
console.error(err); | |
if(err.code === 'LIMIT_FILE_SIZE') { | |
return res.status(400).json({ error: 'File size too large' }); | |
} | |
return res.status(400).json({ error: 'Invalid file' }); | |
} | |
next(); | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
/** | |
* @callback ExpressRouteFn | |
* @param {express.Request} req | |
* @param {express.Response} res | |
* @param {Function} next | |
*/ | |
/** | |
* @param {ExpressRouteFn} fn | |
* @return {ExpressRouteFn} | |
*/ | |
function wrapper (fn) { | |
/** | |
* @param {express.Request} req | |
* @param {express.Response} res | |
* @param {Function} next | |
*/ | |
return function(req, res, next) { | |
return fn(req, res, next).catch((err) => next(err)); | |
} | |
} | |
/** | |
* @param {ExpressRouteFn} fn | |
* @return {ExpressRouteFn} | |
*/ | |
function wrapMulter(multerFn) { | |
return wrapper(async (req, res, next) => { | |
return multerFn(req, res, function(err) { | |
if(err) { | |
console.error(err); | |
if(err.code === 'LIMIT_FILE_SIZE') { | |
return res.status(400).json({ error: 'File size too large' }); | |
} | |
return res.status(400).json({ error: 'Invalid file' }); | |
} | |
next(); | |
}); | |
}); | |
} | |
module.exports = { | |
wrapper, | |
wrapMulter, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment