Skip to content

Instantly share code, notes, and snippets.

@omarwaleed
Last active March 18, 2023 00:01
Show Gist options
  • Save omarwaleed/bf271dc5ee304810ee2d0821d0c637dc to your computer and use it in GitHub Desktop.
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
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();
});
});
}
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