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

@fundaciobit/express-middleware

v1.7.6

Published

A miscellaneous collection of Express middlewares.

Downloads

53

Readme

Miscellaneous Express middlewares

A miscellaneous collection of Express middlewares.

Note: For specific Express middleware wrappers for Redis and MongoDB, please visit @fundaciobit/express-redis-mongo

Middlewares

| middleware | description | |--------------------|-------------------------------------------------------| | ipv4 | Extracts IP address and converts IPv6 format to IPv4. | | parseTypes | Parses string properties into numbers or booleans. | | validateJsonSchema | Validates an instance with a provided JSON Schema. | | verifyJWT | Verify a JSON Web Token. | | signJWT | Sign a JSON Web Token. |

Install

npm install @fundaciobit/express-middleware

Index

ipv4

Middleware to extract the IPv4 address from the request object (it converts IPv6 format to IPv4 format). The extracted address will be available on the request via the ipv4 property.

Usage

const express = require('express')
const { ipv4 } = require('@fundaciobit/express-middleware')

const app = express()

app.use(ipv4())

app.get('/ip', (req, res) => {
  const { ipv4 } = req
  res.json({ ipv4 })
})

app.use((err, req, res, next) => {
  res.status(500).send(err.toString())
})

const port = 3000
app.listen(port, () => { console.log(`Server running on port ${port}...`) })

parseTypes

Middleware to convert string properties of an object to numbers (integers or floats) or booleans. The provided object will not be mutated. The copied and parsed object will be available on the request via parsedObject property.

Parameters

  • objectToParse: (required) Function that accepts the request object as parameter, that returns the object to parse.
  • properties: (optional) Array of properties to parse. If not provided, the conversion is applied to all properties of the object.

Usage

const express = require('express')
const { parseTypes } = require('@fundaciobit/express-middleware')

const app = express()

app.get('/users/min_age/:min_age/max_age/:max_age/is_employee/:is_employee/min_salary/:min_salary/max_salary/:max_salary',
  parseTypes({
    objectToParse: (req) => req.params
  }),
  (req, res) => {
    const { params, parsedObject } = req
    res.status(200).json({ params, parsedObject })
  })

app.use((err, req, res, next) => {
  if (!err.statusCode) err.statusCode = 500
  res.status(err.statusCode).send(err.toString())
})

const port = 3000
app.listen(port, () => { console.log(`Server running on port ${port}...`) })

validateJsonSchema

Middleware to validate the structure of an instance with the provided JSON Schema.

Parameters

  • schema: (required) is a JSON Schema object.
  • instanceToValidate: (required) is a function that accepts the request object as parameter, that returns the 'instance' to validate (string, array or object).

Usage

const express = require('express')
const bodyParser = require('body-parser')
const { validateJsonSchema } = require('@fundaciobit/express-middleware')

const app = express()

app.use(bodyParser.json())

app.post('/login',
  validateJsonSchema({
    schema: {
      type: 'object',
      required: ['username', 'password'],
      properties: {
        username: { type: 'string' },
        password: { type: 'string' },
      },
      additionalProperties: false
    },
    instanceToValidate: (req) => req.body
  }),
  (req, res) => {
    res.sendStatus(200)
  })

app.use((err, req, res, next) => {
  if (!err.statusCode) err.statusCode = 500
  res.status(err.statusCode).send(err.toString())
})

const port = 3000
app.listen(port, () => { console.log(`Server running on port ${port}...`) })

verifyJWT

Middleware to verify a JSON Web Token. The token to verify is extracted from:

  • the Authorization header as a bearer token ( Authorization: Bearer AbCdEf123456 ),
  • or through a token query parameter ( http://...?token=AbCdEf123456 ).

If the token is verified, then the decoded token payload is available on the request via the tokenPayload property, and the control is passed to the next middleware.

Parameters

  • secret: (required) is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA, as described in jsonwebtoken.

Usage

const express = require('express')
const { verifyJWT } = require('@fundaciobit/express-middleware')

const app = express()

app.get('/protected',
  verifyJWT({ secret: 'my_secret' }),
  (req, res) => {
    res.sendStatus(200)
  })

app.use((err, req, res, next) => {
  if (!err.statusCode) err.statusCode = 500
  res.status(err.statusCode).send(err.toString())
})

const port = 3000
app.listen(port, () => { console.log(`Server running on port ${port}...`) })

signJWT

Middleware to sign a JSON Web Token. The signed token will be available on the request via token property.

Parameters

  • payload: (required) is a function that accepts the request object as parameter, that returns an object literal, buffer or string representing valid JSON.
  • secret: (required) is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA, as described in jsonwebtoken.
  • signOptions: (optional) is an object with extra info to encode, as described in jsonwebtoken. Eg: { expiresIn: '24h' }

Usage

const express = require('express')
const bodyParser = require('body-parser')
const { signJWT } = require('@fundaciobit/express-middleware')

const app = express()

app.use(bodyParser.json())

app.post('/login',
  // Here include a middleware to verify user credentials from req.body:
  //  If Ok: set user info in req.user (without password) and call next().
  //  Else: call next(error) to handle the authentication error.
  signJWT({
    payload: (req) => ({
      username:  req.user.username,
      role: req.user.role
    }),
    secret: 'my_secret',
    signOptions: { expiresIn: '24h' }
  }),
  (req, res) => {
    const { token } = req
    res.status(200).json({ token })
  })

app.use((err, req, res, next) => {
  if (!err.statusCode) err.statusCode = 500
  res.status(err.statusCode).send(err.toString())
})

const port = 3000
app.listen(port, () => { console.log(`Server running on port ${port}...`) })