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

@ekino/express-validation

v0.2.0-alpha.0

Published

[![version](https://img.shields.io/npm/v/@ekino/express-validation.svg?style=flat-square)](https://www.npmjs.com/package/@ekino/express-validation)

Downloads

9

Readme

@ekino/express-validation

version

:warning: Work in progress :warning:

This package helps validating/normalizing incoming express API requests using Joi schemas in the form of express middlewares. When you add one of the provided middelwares to your app, it will try to validate the given source (body, path, query, headers) against a Joi schema, replace the source data with the validated data if validation passes or send back the validation errors along with a 400 HTTP status code otherwise.

Please be aware that the provided middlewares mutate the request's source data.

It can be used for several purposes, for example:

  • validating payload when attempting to write to your API
  • validating pagination/filters/sorting when retrieving a list of items
  • validating path parameters such as ids
  • validating tokens present in request headers (not the fact that they actually exists)

It's written in TypeScript, so there's no need to install external types if you're working on a TypeScript based project. However TypeScript is not required as the published package contains a compiled version.

It supports several sources:

You can easily adapt it to your needs using the configuration object.

Installation

You also have to install Joi as it's a peer dependency of this package.

yarn add joi @ekino/express-validation

Usage

Validating request body

import * as Joi from 'joi'
import { validateRequestBody } from '@ekino/express-validation'

app.post('/post', validateRequestBody(schema), (req, res) => {})

Validating request path

import * as Joi from 'joi'
import { validateRequestPath } from '@ekino/express-validation'

const schema = Joi.object().keys({
    id: Joi.number().required()
})

app.get('/post/:id', validateRequestPath(schema), (req, res) => {
    // now you're sure that `id` is a number,
    // it also have been casted to a number
    const { id } = req.params
})

Validating request query

import * as Joi from 'joi'
import { validateRequestQuery } from '@ekino/express-validation'

const schema = Joi.object().keys({
    sort: Joi.string().required()
})

app.get('/posts', validateRequestQuery(schema), (req, res) => {
    // assuming you made a request such as `GET /posts?sort=title`
    // now you're sure that `sort` exists
    const { sort } = req.query
})

Validating request headers

import * as Joi from 'joi'
import { validateRequestHeaders } from '@ekino/express-validation'

app.get('/posts', validateRequestHeaders(), (req, res) => {})

Configuration

You can completely customize the behaviour of the middlewares, this module can act as a simple bridge between Joi & express.

The available options are:

  • joiOptions
  • logger
  • errorStatusCode
  • errorBody
  • errorHandler

Let's now see which use cases can be covered using those options.

Customizing Joi options

Adding logging support

Customizing error response status code

By default, all the middlewares issue a 400 HTTP status code, the errorStatusCode option allows you to use another one.

app.get('/post/:id', validateRequestPath(schema, { errorStatusCode: 404 }), (req, res) => {
    // ...
})

Now, if the provided :id doesn't conform to schema, the client will receive a 404 HTTP status code.

You can also use a function to determine response status code, which can be useful if you have to add some extra logic to define it.

app.get(
    '/post/:id',
    validateRequestPath(schema, {
        errorStatusCode: (req: Request, error: ValidationError) => 401
    }),
    (req, res) => {
        /* ... */
    }
)

Customizing error response body

Using your own error handler