Multer encountering an error due to issues with TypeScript typings

The code snippet below shows my current implementation:

import multer from "multer";
const upload = multer().single('file');
router.post('/add', async (req, res) => {
    upload(req, res, async (err: any) => {
        if (err) {
            res.status(500).send(err.toString())
        }
        else {
            res.status(200).send(await addMedia(req.file.filename))
        }
    })
});

I am currently in the process of determining the appropriate Error type to replace any. However, when I attempted to use MulterError, I encountered the following error message :

Argument of type '(err: MulterError) => Promise' is not assignable to parameter of type 'NextFunction'. Types of parameters 'err' and 'deferToNext' are incompatible. Type 'string' is not assignable to type 'MulterError'.

Using unknown is not feasible due to the .toString() method. While string does work, it does not accurately reflect the type, as further investigation reveals that a MulterError is present.

An additional point of confusion lies with the 3rd parameter of the upload function - this may possibly be contributing to my dilemma.

Answer №1

This is the approach I took to manage errors

const storage: multer.StorageEngine = multer.diskStorage({
    destination: (_req, _file, callback) => {
        const path = `./uploads/`;
        // check and create folder if it doesn't exist
        fs.mkdirSync(path, { recursive: true });
        callback(null, path);
    },
    filename: (_req, file, callback) => {
        callback(null, new Date().toISOString() + file.originalname);
    }
});

const fileLimit = {
    fileSize: 1024 * 1024 * 10 // limit file size to 10MB
};
const fileFilter = (
    _req: Request,
    file: Express.Multer.File,
    callback: FileFilterCallback
) => {
    // send error if file type is not an image
    if (!file || file.mimetype.split('/')[0] != 'image') {
        return callback(new Error('Only images are allowed'));
    }
    callback(null, true);
};

const upload: multer.Multer = multer({
    storage: storage,
    limits: fileLimit,
    fileFilter: fileFilter
});

const galleryUpload = upload.single('galleryImage');
// Upload gallery image
router.post('/', async (req: Request, res: Response) => {
    galleryUpload(req, res, (err: unknown) => {
        if (err instanceof multer.MulterError) {
            // Handle Multer error during upload.
            return res.status(400).send({ message: err.message });
        } else if (err instanceof Error) {
            // Handle unknown error during upload.
            return res.status(400).send({ message: err.message });
        }
        return res.status(200).send({ message: 'Image uploaded successfully' });
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify if an express module has a next() function available

Is there a method to check if there is a function after the current middleware? router.get('/', function(req, res, next){ if(next){//always returns true } }); I have a function that retrieves information and depending on the route, thi ...

I am a beginner in the world of MEAN stack development. Recently, I attempted to save the data from my form submissions to a MongoDB database, but unfortunately, I have encountered

const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = new mongoose.Schema({ username: St ...

What is the proper way to incorporate the "pdf" package into a TypeScript project?

I recently installed pdf and its types using the following command: npm install --save pdf @types/pdf However, I am struggling to find any documentation on how to actually use this package. When I try the following code: import {PDFJS} from 'pdf&ap ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

Creating a personalized news feed using getstream.io in Node.js - a step-by-step guide

const stream = require('getstream'); // Setting up a newsfeed stream using getstream const client = stream.connect( null, ); // Defining a feed for user1 var user1 = client.feed('user', 'user1'); // Adding a custom activity ...

VS 2015 solution loses files upon saving

Following the successful installation of VS 2015 Pro (14.0.25... with Update 3, including a valid license key), and creating a new project (specifically in Javascript or TypeScript using Ionic 2 templates), an issue arises when opening a file. Whether modi ...

What is the best way to extract values from case-sensitive query param variables?

I am dealing with a URL that contains the query string id. However, the variable id can appear as either 'id' or 'Id' in the URL. From my understanding, these two variations will be treated differently. To handle URLs like the followin ...

How to send variables to a function when a value changes in TypeScript and Angular

As someone who is new to Angular and HTML, I am seeking assistance with the following code snippet: <mat-form-field> <mat-select (valueChange)="changeStatus(list.name, card.name)"> <mat-option *ngFor="let i of lists"> {{i.name}} ...

Determine the data type of a property within a JavaScript object

I am currently working with a javascript object that looks like this: venue = { id: 0, name: '', venueimage_set: [ { imageurl: '', }, ]... At a later point in my code, I need to modify the object ...

Calling Array.prototype.slice results in an array with no elements

As a beginner in Javascript, I am looking to save JSON request data to a sub document in a MongoDB database. My current approach involves converting the JSON request into an array and then utilizing the $push method to pass the array to the sub document. H ...

Guide on creating a style instance in a component class using Material-UI and Typescript

After transitioning my function component to a class component, I encountered an error with makeStyle() from Material-UI as it violates the Rule of Hooks for React. The documentation for Material-UI seems to focus mainly on examples and information related ...

Incorrect handling of double quotes within an object in an Angular component file

In this scenario, I have a component called Froala Editor that allows the creation of custom dropdowns. To achieve this, it requires an object in the following format: // Options for the dropdown. options: { 'opt1': 'Option 1', ...

The instantiation of generic types in Typescript

I have been working on a function that aims to create an instance of a specified type with nested properties, if applicable. This is the approach I have come up with so far. export function InitializeDefaultModelObject<T extends object> (): T { ...

Express cookie not being saved in React application by Chrome

Even though I am receiving cookies from my Express app without any warnings, it seems that the cookie is not being stored, as confirmed through Chrome dev tools. The setup involves a React app and an express API: API: https://api.mycompany.com (express: ...

Every time I attempt to start my React app using npm start, I encounter the error message stating "Something is already running on port 3000"

As I ventured into creating a fake REST API using Express JS and deploying it to Heroku today, I found myself following a YouTube tutorial due to my lack of experience. In the app.js file, I added the following code: app.listen(process.env.PORT || 3000, () ...

Is there a way to combine two arrays of objects that may be undefined?

Here is the object I am working with: interface Cart { orderPromo?: ProductPromotion[], productPromo?: ProductPromotion[], } Both properties are of the same type, but they can be undefined. What is the most efficient and clean way to merge them? ...

What is the most efficient way to execute useEffect when only one specific dependency changes among multiple dependencies?

My main objective is to update a state array only when a specific state (loadingStatus) undergoes a change. Yet, if I include solely loadingStatus as a dependency, React throws an error requesting all dependencies [loadingStatus, message, messageArray, set ...

Dealing with Promise Wrapper Already Declared in TypeScript Return TypeMismatch

Here is a snippet of TypeScript code I am working with: type Chain = 'eth' export type ApiMethods = { getToken: { path: 'tokens/' (args: { chain: Chain tokenAddress: EthereumAddress }): string } getRank: ...

Allowing the use of the colon character in Node.js Express routes using Google custom methods

While browsing Google, I stumbled upon a "recommendation" regarding REST custom methods that caught my interest. https://cloud.google.com/apis/design/custom_methods I am facing an issue in Node.js where I need to allow the ':' character in rout ...