Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async
errors by applying .catch
to every static method in the following manner:
// Within user-response.ts
const catchAsyncError = (func: Function) => {
const catcher = (req: Request, res: Response, next: NextFunction) => {
func(req, res, next).catch(next);
}
return catcher;
}
class UserResponse {
static createUser = catchAsyncError(createUser);
static updateUser = catchAsyncError(updateUser);
static deleteUser = catchAsyncError(deleteUser);
// more static methods...
}
// Inside routes.ts
const router = express.Router();
router.post('/create-user', UserResponse.createUser);
router.patch('/update-user', UserResponse.updateUser);
router.delete('/delete-user', UserResponse.deleteUser);
The main objective here is to eliminate redundancy in the code. Note how catchAsyncError(...)
needs to be written repeatedly for each static method.
Additionally, the idea behind organizing these functions within a class is to provide some meaningful context to each function. This way, even a developer unfamiliar with the inner workings of the various user
functions can understand their relationship by seeing UserResponse.createUser
instead of just createUser
.
A solution similar to the following is sought after:
// Within user-response.ts
const catchAsyncError = (func: Function) => {
const catcher = (req: Request, res: Response, next: NextFunction) => {
func(req, res, next).catch(next);
}
return catcher;
}
@withCatchAsyncError
class UserResponse {
static createUser = createUser;
static updateUser = updateUser;
static deleteUser = deleteUser;
// more static methods...
}
How does one implement such a solution? One can only hope it's achievable, as it presents a more elegant and visually pleasing approach compared to the previous one.