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

fastify-zod-validate

v0.2.0

Published

Fastify route handler validation plugin using Zod in TypeScript

Downloads

11

Readme

fastify-zod-validate

CI NPM version

A type-safe validation plugin for Fastify 4.x and Zod, arguably the best TypeScript-first validation library.

Install

npm i -S fastify-zod-validate

Features

  • Opt-in schema validation for each Fastify route via fastify.withTypeProvider()
  • Customize schema validation error when registering the plugin

Assumptions

  • Fastify 4.x and Zod 3.x are already installed in your project

Usage

Thefastify-zod-validate plugin decorates the fastify instance with a withTypeProvider function, which can be used to compile and validate the fastify schemas (comprising HTTP body, path parameters, query parameters, headers and more) using the zod library. You can import the plugin using a default import:

import fastifyZodValidate from 'fastify-zod-validate'
  • Define your schemas using zod:
import { z } from 'zod'

export const UserBody = z.object({
  username: z.string().min(5).max(10),
  balance: z.number().min(1000),
}).strict()
export type UserBody = z.infer<typeof UserBody>

export const UserPathParams = z.object({
  userID: z.string().min(4).max(4),
}).strict()
export type UserPathParams = z.infer<typeof UserPathParams>
  • Define your fastify router with type-safe schema validation built-in:
import { FastifyPluginCallback } from 'fastify'

export const zodValidateRouter: FastifyPluginCallback = (fastify, options, next) => {
  fastify.withTypeProvider().route({
    method: 'POST',
    url: '/user/:userID',
    schema: {
      body: UserBody,
      params: UserPathParams,
    },
    handler: async (request, reply) => {
      // no casting or @ts-ignore required
      const { body, params } = request
      const { userID } = params
  
      await reply.status(200).send({
        data: {
          message: `OK user with ID ${userID}`,
          body,
        },
      })
    }
  })

  next()
}
  • Register the plugin and setup your fastify server:
import fastifyZodValidate from 'fastify-zod-validate'
import Fastify from 'fastify'

export async function setupServer() {
  const server = Fastify()

  // register the plugin
  server.register(fastifyZodValidate, {
    // optional custom validation error handler
    handleValidatorError: (error, data) => {
      const validationError = new Error('Unprocessable Entity - Custom Zod Validation Error')

      // @ts-ignore
      validationError.statusCode = 422
      return { error: validationError }
    },
  })

  // register the router
  server.register(zodValidateRouter, { prefix: 'route' })

  await server.ready()
  return server
}
  • Start your fastify server:
async function main() {
  const server = await setupServer()
  server.listen({ port: 3000 })
}

main()
  • See validation in action:

    The following HTTP request

    {
    curl -0 -X POST http://localhost:3000/route/user/1234 \
    -H "Content-Type: application/json; charset=utf-8" \
    -H "X-User: user" \
    --data-binary @- << EOF
    {
      "username": "invalid, and checked",
      "balance": -1
    }
    EOF
    } | jq '.'

    will be rejected with the following error

    {
      "statusCode": 422,
      "error": "Unprocessable Entity",
      "message": "Unprocessable Entity - Custom Zod Validation Error"
    }

We encourage you to take a look at the __tests__ folder for a more complete example.


🚀 Build and Test package

This package is built using TypeScript, so the source needs to be converted in JavaScript before being usable by the users. This can be achieved by using TypeScript directly:

npm run build

We run tests via Jest:

npm run test

🤝 Contributing

Contributions, issues and feature requests are welcome!Feel free to check issues page. The code is short and tested, so you should feel quite comfortable working on it. If you have any doubt or suggestion, please open an issue.

⚠️ Issues

Chances are the problem you have bumped into have already been discussed and solved in the past. Please take a look at the issues (both the closed ones and the comments to the open ones) before opening a new issue.

🦄 Show your support

Give a ⭐️ if this project helped or inspired you! In the future, I might consider offering premium support to Github Sponsors.

👤 Authors

📝 License

Built with ❤️ by Alberto Schiabel. This project is MIT licensed.