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-fastest-validator

v1.0.7

Published

Fastest request validation library

Downloads

6

Readme

express-fastest-validator

🚀 Fastest express request validation library 🚀

Error handling in a large project has always been a complex task in express projects. express-fastest-validator eases the pain of the developer in handling the invalid API requests. express-fastest-validator is based on the fastest validations js library fastest-validator.

express-fastest-validator provides a request validation middleware which you can plug in your express routes which will validate the express request and throw a Error if any validation rules fails. Yes !! it is this easy to handle invalid requests.

Installation

Install with npm

npm install express-fastest-validator

Install with yarn

yarn add express-fastest-validator

Request Properties

express-fastest-validator supports multiple express request properties

  • body
  • headers
  • params
  • qs
  • query

Schema Definition

express-fastest-validator uses fastest-validator which is the the fastest JS validator library for NodeJS | Browser.

// Schema for validating user login API
const loginSchema = {
  body: {
    username: { type: 'string', min: 3, max: 15 },
    password: { type: 'string', min: 8 },
  },
};

Read complete docs for field types and built-in validators

Validating API

You just need to define your schema and plug it into your API route. This is all you need to do.

const { express } = require('express');
const { validator } = require('express-fastest-validator');

const app = express();

const loginSchema = {
  body: {
    username: { type: 'string', min: 3, max: 15 },
    password: { type: 'string', min: 8 },
  },
};

app.post('/api/user', validator(loginSchema), userController.login);

Error Handling Middleware

Express Middleware provides the power of handling the request response cycle with ease.

Middleware can be used to handle all the API errors within a single peace of code. You can use a middleware to handle all the API errors in your project. You can define your error handling middleware after defining all your routes. This is because we want the error handling middleware to run just before sending the response to check weather the API is returning a valid response or an error.

Read more about Error-handling Middleware

const errorHandler = (err, req, res, next) => {
  /*
   * FXValidationError will be raised by express-fastest-validator if the request is invalid.
   * FXValidationError.description is an array describing validation errors.
   */
  if (err instanceof FXValidationError) {
    res.status(400).send(err.description);
  }

  // APIError is your custom Error class for api errors.
  if (err instanceof MyAPIError) {
    res.status(err.status).send(err.message);
  } else {
    res.status(500).send('something went wrong');
  }
};

// Now you can use this plug this middleware in your express app.
app.use(errorHandler);

Custom Error Handling Example

const express = require('express');
const bodyParser = require('body-parser');
const { validator, FXValidationError } = require('express-fastest-validator');

const PORT = 8000;

const schema = {
  params: {
    username: { type: 'string', min: 3, max: 15 },
  },
  body: {
    age: { type: 'number', positive: true, integer: true },
  },
};

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/user/:username', validator(schema), (req, res) => {
  const { age } = req.body;
  const { username } = req.params;
  res.status(200).send(`Welcome 🔥${username}🔥, you are ${age} years old`);
});

// Set the value of errorHandlerMiddleware to true
app.set('errorHandlerMiddleware', true);

// Error Handling Middleware
app.use((err, req, res, next) => {
  if (err instanceof FXValidationError) {
    // Handle request invalidation error
    res.status(400).send(err.description);
  } else {
    // Handle all the others except request invalidation errors.
    res.status(500).send('something went wrong');
  }
});

app.listen(PORT, () => {
  console.log(`⚡️[server]: Server is running at http://localhost:${PORT}`);
});