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-joi-validators

v1.0.2

Published

Joi validation wrapper middleware for validating express request headers and body.

Downloads

9

Readme

Express Joi Validators (EJV)

Introduction

This is a Joi validation wrapper middleware for validating express request headers and body. All data validated by express-joi-validators is passed to a context object 'ctx' which is set on the request object of express.

1. Getting Started

Here we will show you how to get started with express-joi-validators, through an example. Please follow the steps below to guide you through the process:

  • create a new folder on your desktop
  • navigate into the folder with your CLI. $ cd your_directory_path
  • create a file called index.js
  • copy and paste the example code into your index.js file
  • run npm init -y
  • run npm i express @hapi/joi express-joi-validators
  • run node index.js
  • open http://localhost:5000 in your browser
  • you should now get a response similar to the one given in the example below.

Note: If your version of express is lower than 4.16.0 you will have to install the body-parser package and modify part 3 of the example accordingly.

// PART 1: Setting up express
const express = require('express') 
const app = express()
const server = require('http').createServer(app)
const port = 5000

// PART 2: Require in Joi and express-joi-validators
const Joi = require('@hapi/joi')
const { validateHeader, validateBody } = require('express-joi-validators')

// PART 3: Setting up request JSON and URL parsers. Note: if they are not called, joi will not call next(error)
app.use(express.json()) // This middleware is required for schemas validation to work.
app.use(express.urlencoded({ extended: true }))

// PART 4: Create Joi schema for validating request body
const schema = Joi.object().options({abortEarly: false}).keys({
    username: Joi.string().lowercase().required(),
    password: Joi.string().min(6).required(),
})

// PART 5: Create route with validatorBody mounted
const requestHandler = (req, res) => res.end()
app.use('/', validateBody(schema), requestHandler)


// PART 6: Mount an express errorHandler middleware to catch and handle the Joi validation Error
const errorHandler = (err, req, res, next) => res.status(422).json(err)
app.use(errorHandler) 

// PART 7: Set server to listen for requests
server.listen(port, () => {
    console.log(`server running at http://localhost:${port}`)
})

The code above would yield the response below:

{
    "_original": {},
    "details": [
        {
            "message": "\"username\" is required",
            "path": [
                "username"
            ],
            "type": "any.required",
            "context": {
                "label": "username",
                "key": "username"
            }
        },
        {
            "message": "\"password\" is required",
            "path": [
                "password"
            ],
            "type": "any.required",
            "context": {
                "label": "password",
                "key": "password"
            }
        }
    ]
}

2. Getting the Validated Response Body

If the request passes all validation rules, you access the validated body in your route through req.ctx.body.

example:

app.use('/login', validateBody(loginShema), (req, res) => {
    const { body } = req.ctx
    // your code ...
})

3. Getting the Validated Response Header

If the request passes all validation rules, you access the validated header in your route through req.ctx.header.

example:

app.use('/login', validateBody(loginShema), (req, res) => {
    const { header } = req.ctx
    // your code ...
})