npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-dynamic-middlewares

v1.0.2

Published

An npm package providing custom error handling and asynchronous middleware wrapping for Express applications and also provide data validating middleware.

Downloads

4

Readme

Express Dynamic Middlewares

This npm package acts as a data security guard for your Express applications. It offers validation for incoming data (emails, usernames, etc.) and provides custom error handling. Additionally, it includes middleware wrapping functions to streamline asynchronous operations and enhance your development experience.

Installation

Install the package using npm or yarn:

npm install express-dynamic-middlewares

or

yarn add express-dynamic-middlewares

Usage/Examples

ErrorHandler Class
The ErrorHandler class is a custom error class that extends the native JavaScript Error class. It allows you to specify a statusCode and message for the error.

throw new ErrorHandler(404, "Page not found");

errorHandler Middleware
The errorHandler middleware handles errors thrown in your Express application, providing a standardized JSON response.
Catches all errors thrown in your application routes and returns a JSON response with:

  • success: false to indicate an error
  • error: message containing the error message or a default "Internal server error"
  • Optional statusCode for specific error classification (defaults to 500)
  • Make sure to use this middleware after all routes
app.use(errorHandler);

asyncHandler Middleware
The asyncHandler middleware wraps asynchronous functions to catch errors and pass them to the next middleware. This helps in keeping your route handlers clean and free from try-catch blocks. It takes two arguments one is function and second is Array to handle specific errors. Array is optional argument.

app.get("/get", asyncHandler(getFunction));

Optional Error Handling Array: Customize error handling by providing an optional array as the second argument to asyncHandler. This array lets you define specific error types and their corresponding HTTP status codes and messages.

const errorOptions = [
    {
        type: TypeError,
        statusCode: 400,
        message: "Bad request due to type error",
    },
];

app.get("/data", asyncHandler(getData, errorOptions)); // getData is your asynchronous function

validator Middleware
The validator function creates a middleware for validating parameters in request body.

app.post(
    "/register",
    validator(
        "username", //Make sure that request body contain username
        true, // (true means check for emptiness or existence)(Optional)(Default : true)
        false, // (false means don't check for whether it's an email or not)(Optional)(Default : false)
        5, // Minimum length(Optional)(Default : 0)(When 0 don't check for minLenght)
        20, // Maximum length(Optional)(Default : 0)(When 0 don't check for maxLength)
        false // (false means don't check for whether it's phone no. or not)(Optional)(Default : false)
    ),
    asyncHandler(registerUser)
);

Additional Validation Middlewares: For your convenience, express-dynamic-middlewares offers pre-built validation middlewares like validateString, validateNumber, and validateBoolean.

app.get(
    "/get",
    validateString("name"),
    validator("name", true, false, 5, 20, false),
    asyncHandler(getFunction)
);

Example

const express = require("express");
const {
    ErrorHandler,
    errorHandler,
    asyncHandler,
    validator,
} = require("express-dynamic-middlewares");

const app = express();

//All routes
app.post(
    "/register",
    validator("email", true, true, 0, 0, false),
    asyncHandler(async (req, res) => {
        //Throw error
        if (username === "[email protected]") {
            throw new ErrorHandler(
                403,
                "This email is not allowed for registration."
            );
        }
        res.json({ success: true, message: "User registered successfully!" });
    })
);

app.use(errorHandler);

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Handling Custom Errors

To handle specific error types, you can customize one array. This array should contain objects with type, statusCode, and message properties. Add this logic inside your project where asyncHandler is used.

const express = require("express");
const {
    ErrorHandler,
    errorHandler,
    asyncHandler,
} = require("express-dynamic-middlewares");

const app = express();

const errorTypes = [
    {
        type: TypeError,
        statusCode: 400,
        message: "Type error occurred",
    },
    {
        type: ReferenceError,
        statusCode: 500,
        message: "Reference error occurred",
    },
    {
        type: CastError,
        statusCode: 400,
        message: "Cast error occurred",
    },
];

const getFunction = asyncHandler(async (req, res) => {
    //function...
}, errorOptions); //Pass error options to handle perticular errors

//All routes
app.get("/data", getFunction);

app.use(errorHandler);

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

License

MIT

Authors

@Dev Patel