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-promisify-router

v1.1.0

Published

Write Express middleware and route handlers using async/await

Downloads

5

Readme

express-promisify-router

Express-promisify-router is a lightweight JavaScript library with zero dependencies that enables async/await support in Express framework applications. With this library, you can write both middleware and routes using async/await syntax. It allows you to return promises directly from route handlers without the need for a try-catch block, simplifying error handling and data transmission to the client.

Installation

npm i express-promisify-router

npm version

Usage:

Using Router()

Creates a new async router instance using Router(). This method simplifies the process of creating an async router.

// Usage Example: use wrapped Router()
const { Router } = require('express-promisify-router');
const router = Router();

router.get('/foo', async (req, res, next) => {
    const user = await UserService.findById();
    if (!user) {
        throw new NotFound('User not found');
    }
    return users;
});

Using wrapRouter()

Wraps an existing Express router instance to add async/await support. This method is useful when you already have an Express router instance and want to add async/await support to it.

// Usage Example: use wrapRouter()
const express = require('express');
const { wrapRouter } = require('express-promisify-router');
const router = wrapRouter(express.Router());

router.get('/foo', async (req, res, next) => {
    const user = await UserService.findById();
    if (!user) {
        throw new NotFound('User not found');
    }
    return users;
});

Using route()

Provides a more structured way to define routes and their handlers using the route() method. This method allows you to define multiple HTTP methods for a single route.

const { Router } = require('express-promisify-router');
const router = Router();

router
    .route('/foo')
    .get((req, res, next) => {
        return UserService.fetch();
    })
    .post((req, res, next) => {
        return UserService.create();
    });

Returning Data Directly

Allows you to return data directly from the route handler without explicitly calling res.send(). This simplifies the process of sending responses to clients.

const express = require('express');
const { wrapRouter } = require('express-promisify-router');
const router = wrapRouter(express.Router());

router.get('/foo', async (req) => {
    return await new Promise((resolve) => {
        resolve({ message: 'Hello!' });
    });
});

Using Array of Middlewares

Enables you to use an array of middleware functions for a single route. Each middleware function in the array will be executed sequentially.

const express = require('express');
const { wrapRouter } = require('express-promisify-router');
const router = wrapRouter(express.Router());

router.get('/foo', [
    (req, res, next) => {
        next();
    },
    async (req, res, next) => {
        throw new Error('Exception!');
    }
]);

Using Classic Middleware Approach

Demonstrates the classic middleware approach for defining route handlers. This method is useful when you need more control over the error handling process.

const express = require('express');
const { wrapRouter } = require('express-promisify-router');
const router = wrapRouter(express.Router());

router.get('/foo', [
    (req, res, next) => {
        next();
    },
    (req, res, next) => {
        try {
            res.send();
        } catch (err) {
            next(err);
        }
    }
]);

Support for router.param

RouterWrapper class supports Express's router.param method. This allows you to add middleware functions that will be invoked when a route parameter is matched. For example, you can define a router.param middleware for the userId parameter like this:

router.param(
    'userId',
    wrapFunction(async (req, res, next, userId) => {
        const user = await User.findById(userId);
        if (!user) {
            const error = new Error('User not found');
            error.status = 404;
            throw error;
        }
        req.user = user;
        next();
    })
);

This middleware will be invoked whenever a route with the :userId parameter is matched. It allows you to perform operations like validating and loading the user data before the route handler is invoked.

API

wrapRouter()

The wrapRouter() function is the best way to add async/await support to your Express app or Router.

wrapFunction()

If you need more control, you can use the wrapFunction() function. This function wraps an async Express middleware and adds async/await support.