fastest-validator-express
TypeScript icon, indicating that this package has built-in type declarations

1.1.3 • Public • Published

faster-validator-express

faster-validator-express is a middleware for request validation in Express.js. It provides a simple and efficient way to validate incoming requests based on predefined schemas. This middleware using cebob/fastest-validator as the root validator . This README serves as a guide to help you integrate and use the faster-validator-express package in your Express.js project.

cebob/fastest-validator

Installation

Install the package using npm:

npm install faster-validator-express

or

yarn add faster-validator-express

Usage

Configuration

const express = require('express');
const validator = require('faster-validator-express');
const app = express();

let opts={
  schema: {
    user: {
      get: {
        _: "query", //query, body, params
        username: "string"
      }
    }
  },
  rootPath: "/api",
  customError: true
}

app.use(validator(opts));

schema: Defines the validation rules for different endpoints. In this example, the "user" endpoint has a validation rule for the "get" method, expecting a "username" parameter in the query string.

rootPath: Specifies the root path for the API. In this case, it is set to "/api".

customError: Indicates whether custom error handling is enabled. If set to true, a custom error handler will be used.

API Endpoint

A sample API endpoint is created to handle GET requests at /api/user/get. The endpoint simply responds with "ok" for demonstration purposes.

app.get("/api/user/get", (req, res) => {
  return res.send("ok");
});

Custom Error Handling

Custom error handling is implemented using the following middleware:

app.use((err, req, res, next) => {
  err = JSON.parse(err.message);
  return res.status(err.code).send(err);
});

This middleware parses the error message and sends a response with the corresponding HTTP status code and error details.

Package Sidebar

Install

npm i fastest-validator-express

Weekly Downloads

0

Version

1.1.3

License

ISC

Unpacked Size

20.2 kB

Total Files

7

Last publish

Collaborators

  • hoptv