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

@dry-express-responses/zod-request-validation

v2.0.12

Published

ExpressJS middleware to reduce boilerplate in response creation

Downloads

8

Readme

Credit to packages used in this project

  • zod - https://github.com/colinhacks/zod
  • yup - https://github.com/jquense/yup
  • http-status-codes
    • https://github.com/prettymuchbryce/http-status-codes
  • express - https://github.com/expressjs/express
  • express-async-errors
    • https://github.com/davidbanham/express-async-errors

Description

A small wrapper around zod's parse and safe parse to streamline validating a request's body, params, or query, and returning a typesafe version of the objects. Works best with @dry-express-responses/errors and @dry-express-responses/zod.

How to use

Step 1

Install @dry-express-responses/zod-request-validation

npm install @dry-express-responses/zod-request-validation
yarn add @dry-express-responses/zod-request-validation
pnpm add @dry-express-responses/zod-request-validation

Step 2 (optional)

In addition to validation using zSafeParse, an optional global error handler middleware dryExpressErrors with @dry-express-responses/errors, and a custom zod validation error ZodValidationError with @dry-express-responses/zod are available. The zParse function throws ZodValidationError under the hood.

npm install @dry-express-responses/errors @dry-express-responses/zod
yarn add @dry-express-responses/errors @dry-express-responses/zod
pnpm add @dry-express-responses/errors @dry-express-responses/zod

Example usage

import {dryExpressResponses} from '@dry-express-responses/core';
import {
	dryExpressErrors,
	BadRequestError
} from '@dry-express-responses/errors';
import {ZodValidationError} from '@dry-express-responses/zod';
import express from 'express';
import z from 'zod';
import {
	zParse,
	zSafeParse
} from "@dry-express-responses/zod-request-validation";

const app = express();

app.post('/zod-parse', (req, res) => {
	// Throws ZodValidationError when validation fails.
	const {body} = zParse(
		// Can be one of the properties or all of them (body/params/query).
		z.object({
			body: z.object({
				name: z.string(),
			}),
			params: z.object({
				id: z.string().uuid(),
			}),
			query: z.object({
				// Will always return a string!
				page: z.preprocess((value) => {
					if (typeof value !== 'string') return value;

					try {
						return value ? JSON.parse(value) : value;
					} catch {
						return value;
					}
				}, z.number()),
			}),
		}),
		req
	);

	// Typesafe with autocomplete!
	res.send(body.name);
});

app.post('/zod-safe-parse', (req, res) => {
	const result = zSafeParse(
		// Can be one of the properties or all of them (body/params/query).
		z.object({
			body: z.object({
				name: z.string(),
			}),
			params: z.object({
				id: z.string().uuid(),
			}),
			query: z.object({
				// Will always return a string!
				page: z.preprocess((value) => {
					if (typeof value !== 'string') return value;

					try {
						return value ? JSON.parse(value) : value;
					} catch {
						return value;
					}
				}, z.number()),
			}),
		}),
		req
	);

	// Checking if the result is success asserts that body/query/params are on the result object.
	if (!result.success) {
		// Uses express-async-errors under the hood
		throw new ZodValidationError(result.error);
	}
	;

	// Typesafe with autocomplete!
	res.send(result.body.name);
});

app.listen(3000, () => console.log('listening on port 3000'));