Implementing Multer using a Controller/Model Pattern — Typescript

Daniel Glover
3 min readMay 18, 2021

If you’re not familiar with Multer

Multer is a node.js middleware used to handle multipart/form-data and is commonly used to upload images to a node.js website. In other words, handles images uploaded to your website. https://www.npmjs.com/package/multer

In this article post I’ll be taking the standard implementation of multer and transitioning that implementation into a different design pattern. Aiming to demonstrate how to use multer middleware in a model/controller structured program specifically for typescript.

This is an example of the standardised implementation of multer middleware.

As seen above in the screenshot, middleware gets passed in as per usual and works fine, however passing middleware like this in the M/C pattern doesn’t work. In the screenshot below the userController class is using a decorator that wraps the class changing its behaviour so that it can evaluate similarly to the line above. There are various different decorators made for http requests, to implement middleware(@use), validate data on the request body. Middleware has been attached to the uploadFile method in the example below. // uploadMiddleware & checkForAuth

Implementation of middleware using Controller/Model Typescript pattern

The upload variable is set to create an avatars folder, and handle some validation/limitation on that process, so when we do upload an image we can assure its the correct type, storing the image correctly etc, it will also attach a property to the request // req.file.

setting up Multer.

The following code demonstrates how to set up the middleware. In order to handle async express/express errors effectively I’m using try/catch statements and wrapping the multer logic in a Promise, so if they trigger in the middleware they pass the errors down to the routeHandler correctly. The code below comes from the following article detailing how to wrap multer in a promise. It’s simple and effective.

As seen below, the uploadMiddleware (the middleware the method uses), provides the try/catch statement, handling the passing of errors to the response or if the promise is resolved, req.file will available on the request.

Built in MulterErrors will still trigger, but also errors thrown from the fileFilter check will also be thrown and passed as JSON in the response too.

--

--