@zodyac/zod-express
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

Zod Express validator

npm version NPM Downloads npm bundle size

This package provides a set of usefull Express tools for REST request validation with zod (body, parameters and query) based on Matt Pocock's (💜) solution.

Installation

As simple as:

npm i @zodyac/express

pnpm add @zodyac/express

yarn add @zodyac/express

bun add @zodyac/express

Usage

Validating body

Define your request body schema:

import { z } from "zod";

const zBody = z.object({
  // ... your zod schema
});

Create an endpoint using CheckBody function:

const my_endpoint = CheckBody(zBody, (req, res) => {
  const body = req.body;
  // ... the rest of your code
});

Validating parameters

You can also parse your request parameters using CheckParams:

const my_endpoint = CheckParams(zParams, (req, res) => {
  const params = req.params;
  // ... the rest of your code
});

Validating query parameters

And query parameters using CheckQuery:

const my_endpoint = CheckQuery(zQuery, (req, res) => {
  const query = req.query;
  // ... the rest of your code
});

As you can see, req.body, req.params and req.query are inferring types from your zod schema.

Please remember that Express params and query parameters are always strings. If you want to parse them to other types, you have to do it manually.

Validating all at once

But what if... We want to validate all of them at once? No problem, just use Check:

const my_endpoint = Check(
  {
    body: zBody,
    params: zParams,
    query: zQuery,
  },
  (req, res) => {
    const body = req.body;
    const params = req.params;
    const query = req.query;
    // ... the rest of your code
  }
);

Error handling

If validation fails, Check, CheckBody, CheckParams and CheckQuery will automatically send 406 response with error message. If you want to handle errors yourself, you can use ValidationOptions:

const my_error_handler: ze.ValidationOptions = {
  errorCode: 400, // default is 406 (Not Acceptable)
  errorHandler: (req, res, error) => {
    // error is zod Error
    const error_message = error.errors[0].message;
    // ... your error handling code
  },
};

const my_endpoint = Check(
  {
    body: zBody,
    params: zParams,
    query: zQuery,
  },
  (req, res) => {
    const body = req.body;
    const params = req.params;
    const query = req.query;
    // ... the rest of your code
  },
  my_error_handler
);

ValidationOptions interface:

type ErrorHandler = (req: Request, res: Response, error: z.ZodError) => void;

interface ValidationOptions {
  errorCode?: number;
  errorHandler?: ErrorHandler;
}

Middleware

If you prefer to validate your requests aside from your endpoints logic, you can use zem.Body, zem.Params, zem.Query or zem.Check middleware:

import { zem } from "@zodyac/express";

const my_endpoint = (req: Request, res: Response) => {
  const body = req.body;
  const params = req.params;
  const query = req.query;
  // ... the rest of your code
};

app.post("/my_endpoint", zem.Body(zBody), my_endpoint);
app.get("/my_endpoint/:id", zem.Params(zParams), my_endpoint);
app.get("/my_endpoint", zem.Query(zQuery), my_endpoint);

app.put(
  "/my_endpoint",
  zem.Check({
    body: zBody,
    params: zParams,
    query: zQuery,
  }),
  my_endpoint
);

In this case your req.body, req.params and req.query will be any. If you want to use types, you have to specify them manually or use CheckBody, CheckParams, CheckQuery or Check.

Experimental: decorators

You can also use decorators to validate your requests. Just add @ValidateBody, @ValidateParams, @ValidateQuery or @Validate to your endpoint function:

export class Example {
  @ValidateBody(zBody)
  public static my_endpoint(req: Request, res: Response) {
    const body = req.body as z.infer<typeof zBody>;
    // ... the rest of your code
  }
}

Due to the limitations of TypeScript decorators, you have to specify the type of req.body manually.

Contributing

Feel free to open issues and pull requests! Here's a quick guide to get you started:

  • Fork the repository
  • Install linter and formatter for VSCode: Biome
  • Install dependencies: npm i
  • Make changes
  • Run tests: npm test (not implemented yet)
  • Run linter: npm run lint (fix with npm run lint:fix)
  • Commit and push your changes
  • Open a pull request

License

MIT

Package Sidebar

Install

npm i @zodyac/zod-express

Weekly Downloads

15

Version

1.2.0

License

MIT

Unpacked Size

71.8 kB

Total Files

11

Last publish

Collaborators

  • bebrasmell