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-superstruct

v1.1.1

Published

An express validation middleware that uses superstruct

Downloads

4

Readme

express-superstruct

An express validation middleware that uses superstruct

  • Replaces the incoming req.body, req.query, with the validated result, original values are kept inreq._body/req._query
  • Express error middleware will be executed upon validation error

Install

npm install express-superstruct

Usage

const { validate } = require('express-superstruct');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// without req.body/req.query filled, nothing will be validated.
app.use(bodyParser.json());

app.post(
	'/item', 
	validate({ title: 'string', stock: 'number' }),
	(req, res, next) => {
		console.log(req.body.title); // I'm a string 100%
		console.log(req.body.stock); // I'm a number 100%
		res.end('ok');
	}
);

app.get(
	'/item', 
	// Number does not work for GET, since everything is a string/array
	// You may need a custom numeric type. (See below)
	validate({ id: 'string' }),
	(req, res, next) => {
		res.end('ok');
	}
);

Advanced usage

Besides superstruct's built-in types, you can build custom ones!


const { validate, superstruct, struct } = require('express-superstruct');
/* ... */

const types = {
	email: value => isEmail(value),
	passwod: value => validatePassword(value),
	numeric: value => isNumeric(value)
};

const customStruct = superstruct({ types });

const schema = {
	email: 'email', 
	password: 'password',
	captcha: 'boolean?' // Optional field
};

app.post(
	'/login', 
	validate(schema, customStruct),
	(req, res, next) => {
		res.end('ok');
	}
);

app.post(
	'/emails', 
	validate({ emails: ['email'] }, struct),
	(req, res, next) => {
		console.log(req.body.emails); // I'm an array of emails
		res.end('ok');
	}
);

You can pass a more complex Struct too!

const schema = {
	name: 'string & !empty', // !empty may be another custom type!
	emails: struct.optional(['email'])
};

app.post(
	'/user/update', 
	validate(schema, struct),
	(req, res, next) => {
		res.end('ok');
	}
);

/* ... */

Default values are supported:

const schema = [{
	name: 'string & !empty', // !empty may be another custom type!
	emails: struct.optional(['email']),
	foo: struct.optional(['string'])
}, { foo: 'bar' } ];

app.post(
	'/user/update',
	validate(schema, struct),
	(req, res, next) => {
	    // req.body.foo === 'bar' if foo is not send in the request
		res.end('ok');
	}
);

/* ... */

Handling validation error

const { validate, ValidationError } = require('express-superstruct');
const express = require('express');
const app = express();

app.post(...);

app.use((err, req, res, next) => {

	// If you want to set a custom error
	if(err instanceof ValidationError) {
		return res
			.status(400)
			.json({ message: err.message }); // Superstruct's verbose message
	}

});