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

fastest-expressjs-validator

v1.0.3

Published

fastest-expressjs-validator is a robust and easy-to-use middleware package for Express.js applications that simplifies request validation. With this package, you can effortlessly define validation schemas for request body, URL parameters, and query parame

Downloads

695

Readme

fastest-expressjs-validator 🚀

🚀 Effortless Request Validation for Express.js

Description

fastest-expressjs-validator simplifies request validation in Express.js applications. Define schemas for request bodies, URL parameters, and query parameters with ease. Improve the reliability and security of your Express API effortlessly. It leverages the power of the fastest-validator library to validate incoming requests efficiently.

Features

✅ Define validation schemas for body, params, and queries.

✅ Enhanced security and reliability for your Express API.

✅ Customizable validation options.

✅ Support for asynchronous and synchronous validation.

✅ Detailed error messages and structured responses for validation errors.

✅ High performance with minimal code usage.

✅ Written in TypeScript for enhanced type safety and developer experience.

Installation

You can install fastest-expressjs-validator using bun or npm or yarn:

Using bun:

bun add fastest-expressjs-validator

Using npm:

npm install fastest-expressjs-validator

Using yarn:

yarn add fastest-expressjs-validator

Functions and Arguments

validateRequest

A middleware function for request validation in Express.js.

  • Arguments:
    • schema: SchemaType: The validation schema for the request.
    • validateOptions: ValidateOptions = body The type of request ("body", "params", "query", "headers") to validate (default is "body").
    • validatorOptions: ValidatorOptions = { haltOnFirstError: true }: Custom validation options (default options include halting on the first error).

Request Validation Options

When using this middleware, you have the flexibility to specify the type of request you want to validate (e.g., "body," "params," "query," or "headers"). Here are the objects for validateOptions:

Query Validation

const query = {
  requestType: "query",
  multiRequest: false,
};

Params Validation

const params = {
  requestType: "params",
  multiRequest: false,
};

Body Validation

const body = {
  requestType: "body",
  multiRequest: false,
};

Headers Validation

const headers = {
  requestType: "headers",
  multiRequest: false,
};

validateMultiRequest

A utility function for validating multiple request types.

  • Arguments:
    • schema: SchemaType: The validation schema for the request.
    • validateOptions: is not required! Automatically detects default options.
    • validatorOptions: ValidatorOptions = {}: Custom validation options.
type SchemaType = ValidationSchema | MultiValidationSchema;

Usage

Importing the package

const {
  validateRequest,
  validateMultiRequest,
  query,
} = require("fastest-expressjs-validator");
// or
import {
  validateRequest,
  validateMultiRequest,
  query,
} from "fastest-expressjs-validator";

Middleware for Single Request Type

// Define a validation schema
const schema = {
  username: "string",
  password: "string",
};

// Use the middleware in your Express route
app.post("/login", validateRequest(schema), (req, res) => {
  // Your route logic here
});

OR;

const qSchema = {
  q: "string",
};

const validateQuery = validateRequest(qSchema, query);

app.get("/", validateQuery, (req, res) => {
  // ... your code here
});

Middleware for Multiple Request Types

// Define a validation schema
const multiSchema = {
  body: {
    username: "string",
    password: "string",
  },
  params: {
    id: "number",
  },
};

// Use the middleware in your Express route
app.put("/user/:id", validateMultiRequest(multiSchema), (req, res) => {
  // Your route logic here
});

More code examples

validationMiddleware.ts

import {
  MultiValidationSchema,
  ValidationSchema,
  validateMultiRequest,
  validateRequest,
  query,
  params,
} from "fastest-expressjs-validator";

const querySchema: ValidationSchema = {
  name: "string",
  $$strict: true,
};

const bodySchema: ValidationSchema = {
  userName: "string",
  password: "string",
  email: "email",
  $$strict: true,
};

const paramsSchema: ValidationSchema = {
  id: "string",
  $$strict: true,
};

const multiSchema: MultiValidationSchema = {
  body: {
    userName: "string",
    password: "string",
    email: "email",
    $$strict: true,
  },
  query: {
    randomStr: "string",
    $$strict: true,
  },
};

const headerParamSchema: MultiValidationSchema = {
  headers: {
    hasauth: "string",
  },
  params: {
    id: "string",
  },
};

export const validateQuery = validateRequest(querySchema, query);

export const validateBody = validateRequest(bodySchema);
export const validateParams = validateRequest(paramsSchema, params);

export const validateMultiReq = validateMultiRequest(multiSchema);

export const validateHeaderParams = validateMultiRequest(headerParamSchema);

app.ts

import crypto from "node:crypto";
import express from "express";
import {
  validateBody,
  validateHeaderParams,
  validateMultiReq,
  validateParams,
  validateQuery,
} from "./validationMiddleware";

const app = express();

app.disable("x-powered-by");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const hashPassword = (password: string) => {
  const salt = crypto.randomBytes(16).toString("hex");
  return crypto.pbkdf2Sync(password, salt, 1000, 64, "sha512").toString("hex");
};

app.get("/", validateQuery, (req, res) => {
  const { name } = req.query;
  res.status(200).json({
    message: `Validation working! From ${name}`,
  });
});

app.post("/login", validateBody, (req, res) => {
  const { userName, password, email } = req.body;
  const hashedPassword = hashPassword(password);
  res.status(200).json({
    userName,
    email,
    password: hashedPassword,
  });
});

app.get("/getUser/:id", validateParams, (req, res) => {
  const { id } = req.params;
  res.status(200).json({
    message: `User found! : ${id}`,
  });
});

app.post("/signup", validateMultiReq, (req, res) => {
  const { userName, password, email } = req.body;
  const { randomStr } = req.query;
  const hashedPassword = hashPassword(password);

  res.status(201).json({
    userName,
    email,
    randomStr,
    password: hashedPassword,
  });
});

app.post("/headers/:id", validateHeaderParams, (req, res) => {
  const { hasauth } = req.headers;
  const { id } = req.params;
  res.status(200).json({ hasauth, id });
});

app.listen(3001, () =>
  console.log(`App is listening on http://localhost:3001`)
);

See More About Schemas and All Details

For more details on Documentation.

License

This package is open-source and available under the MIT License.