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

@wunderland/express-harness

v1.0.2

Published

A fully typed, light-weight, unopinionated and no-dependencies Express.JS middleware that helps with the validation of requests.

Downloads

22

Readme

express-harness

A fully typed, light-weight, unopinionated and no-dependencies Express.JS middleware that helps with the validation of requests.

In general, as a developer,

  • You provide a validation schema that has the following attributes:

    • Where to look (query, body etc..)
    • What to look (field names)
    • Whether it's required or not
    • Defines your own validation logic against this field.
  • This middleware will then validate the request with the schema, and if it fails, it'll return the request with 400 (by default).

Installation

npm i @wunderland/express-harness

or

yarn add @wunderland/express-harness

Examples

Basic Example

import { validateRequest } from "@wunderland/express-harness";
import express from "express";

const app = express();

app.post(
  "/",
  validateRequest({ body: { user_id: { required: true } } }),
  (request, response) => {
    return response.status(200).json({ user_id: request.body.user_id });
  }
);

Response

{
  "error": "Validation for the following fields are failed",
  "fields": {
    "body": {
      "user_id": "user_id is required"
    }
  }
}

Custom Validation

import { validateRequest } from "@wunderland/express-harness";
import express from "express";

const app = express();

app.post(
  "/",
  validateRequest({
    body: {
      user_id: {
        required: true,
      },
      age: {
        required: false,
        validator: (request) => {
          const {
            body: { age = 5 },
          } = request;
          if (Number(age) < 10) {
            return `You must be at least 10 years old`;
          }
          return undefined;
        },
      },
    },
  }),
  (request, response) => {
    return response.status(200).json({ user_id: request.body.user_id });
  }
);

Response

{
  "error": "Validation for the following fields are failed",
  "fields": {
    "body": {
      "age": "You must be at least 10 years old",
      "user_id": "user_id is required"
    }
  }
}

API

express-harness exports a named function:

validateRequest(schema, [options])

This validateRequest method will validate the express request against the specified schema and will return a 400 with a default error message (which is configurable through options).

schema

The schema is a normal Object that has the following type definition:

Validation Schema Type

type ValidateRequestSchema = {
  body?: {
    [key: string]: {
      required: boolean;
      validator?: ValidatorFunction;
    };
  };
  query?: {
    [key: string]: {
      required: boolean;
      validator?: ValidatorFunction;
    };
  };
  files?: {
    [key: string]: {
      required: boolean;
    };
  };
  params?: {
    [key: string]: {
      required: boolean;
      validator?: ValidatorFunction;
    };
  };
};

Custom Validation ( ValidatorFunction )

You can specify your own validation logic against the fields using this validator method.

When specified, this will be invoked with the following argument signature:

type ValidatorFunction = (request: Request) => string | undefined;

If this validator function returns a string, it'll be treated as an error, and the returned string will be used as the error message. If it's undefined, then it'll be considered as no-error.

options [object]

Through options, you can configure the HTTP Error Code and format the error response according to your needs. It also does the cleaning of saved files (through Multer) in case any of the validation fails (fail fast)

type ValidateRequestOptions = {
  errorCode: number;
  formatErrorPayload: (fields: Fields) => any;
  cleanupMulter: boolean;
};

cleanupMulter: [boolean] (defaults to true)

Delete the saved files (by multer) in case any validation fails.

errorCode [number] (defaults to 400)

The HTTP status code to return on error. You can set any number (although 400 is the preferred).

formatErrorPayload [function] (defaults to a built-in formatter)

This is a helper function that'll let you to customize the error response before sending it to the client.

When provided, this function will get invoked with an object as its param which has the following signature:

type Fields = {
  body: { [key: string]: string | undefined };
  query: { [key: string]: string | undefined };
  params: { [key: string]: string | undefined };
  files: { [key: string]: string | undefined };
};

Contribution

There's a pretty high-chance where we might've missed many issues. If you find one, please feel free to fork and submit a patch

License

This library is licensed under MIT