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

middleware-props

v1.0.2

Published

elegantly consume props attached by middlwares in your routes

Downloads

3

Readme

middleware-props

elegant way to consume middleware props in your routes

Problem

usually for express applications we attach some properties to req in middleware like req.user = user

// below middleware attaches user property to req
const authenticateUser = (req: Request, res: Response, next: NextFunction) => {
  try {
    const cookie = req.headers.cookie ?? '';
    const user = getCurrentUser(cookie);
    req.user = user;
    next();
  } catch (err) {
    next(err);
  }
};

// in subsequent middlewares and routes we can use req.user
app.get('/', authenticateUser, (req, res, next) => {
  try {
    const user = req.user;
    res.json(user);
  } catch (err) {
    next(err);
  }
});

but above method becomes complicated once we start having middleware chain and it becomes hard to track which middleware attached which properties

this package solves this problem

Usage

addProps and getProps methods

basic

import express, { NextFunction, Request, Response } from 'express';

import { addProps, getProps } from '../lib/methods';

namespace Middlewares {
  export type AuthenticateUser = {
    user: User;
  };
}

type User = {
  id: number;
  name: string;
};

const getCurrentUser = (cookie: string): User => {
  // some logic to get the user based on cookie
  const user = {
    name: 'Dummy',
    id: 12,
  };
  return user;
};

const authenticateUser = (req: Request, res: Response, next: NextFunction) => {
  try {
    const cookie = req.headers.cookie ?? '';
    const user = getCurrentUser(cookie);
    const props: Middlewares.AuthenticateUser = { user };
    addProps(req, props, 'authenticateUser');
    next();
  } catch (err) {
    next(err);
  }
};

const app = express();
app.use(express.json());
app.get('/', authenticateUser, (req, res, next) => {
  try {
    const { user } = getProps<Middlewares.AuthenticateUser>(
      req,
      'authenticateUser'
    );
    res.json(user);
  } catch (err) {
    next(err);
  }
});

const PORT = 8000;

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}`);
});

using multiple middlewares

import express, { NextFunction, Request, Response } from 'express';

import { addProps, getProps } from '../lib/methods';

type User = {
  id: number;
  name: string;
};
type Role = 'guest' | 'user' | 'admin';

namespace Middlewares {
  export type AuthenticateUser = {
    user: User;
  };
  export type AttachRole = {
    role: Role;
  };
}

const getCurrentUser = (cookie: string): User => {
  // some logic to get the user based on cookie
  const user = {
    name: 'Dummy',
    id: 12,
  };
  return user;
};

const authenticateUser = (req: Request, res: Response, next: NextFunction) => {
  try {
    const cookie = req.headers.cookie ?? '';
    const user = getCurrentUser(cookie);
    const props: Middlewares.AuthenticateUser = { user };
    addProps(req, props, 'authenticateUser');
    next();
  } catch (err) {
    next(err);
  }
};

const getRole = (user: User): Role => {
  return 'admin';
};

/**
 *
 * dependencies: authenticateUser
 */
const attachRole = (req: Request, res: Response, next: NextFunction) => {
  try {
    // since attachRole middleware is used after authenticateUser middleware
    // we can use properties attached by authenticateUser middleware
    const { user } = getProps<Middlewares.AuthenticateUser>(
      req,
      'authenticateUser'
    );
    addProps<Middlewares.AttachRole>(
      req,
      {
        role: getRole(user),
      },
      'attachRole'
    );
    next();
  } catch (err) {
    next(err);
  }
};

const app = express();
app.use(express.json());
app.get('/', authenticateUser, attachRole, (req, res, next) => {
  try {
    const { user } = getProps<Middlewares.AuthenticateUser>(
      req,
      'authenticateUser'
    );
    const { role } = getProps<Middlewares.AttachRole>(req, 'attachRole');
    res.json({ user, role });
  } catch (err) {
    next(err);
  }
});

const PORT = 8000;

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}`);
});

getAllProps method

const req = {
  body: {},
};

// inside first middleware
addProps<Middlewares.AuthenticateUser>(
  req,
  {
    user: {
      name: 'dummy',
      id: 1,
    },
  },
  'authenticateUser'
);

// inside second middlware
const { user: authenticatedUser } = getProps<Middlewares.AuthenticateUser>(
  req,
  'authenticateUser'
);
const getRole = (user: User): Role => {
  return 'admin';
};

addProps<Middlewares.AttachRole>(
  req,
  {
    role: getRole(authenticatedUser),
  },
  'attachRole'
);

const result = getAllProps(req);
/*
    {
      authenticateUser: { user: { name: 'dummy', id: 1 } },
      attachRole: { role: 'admin' },
    }
*/

More

visit samples directory https://github.com/rgsk/middleware-props/tree/main/src/samples

visit base.test.ts file to see advanced use-cases supported https://github.com/rgsk/middleware-props/blob/main/src/base.test.ts