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-query-coercion

v1.0.0

Published

A Fastify plugin that automatically converts query parameter types based on Zod schemas

Downloads

100

Readme

fastify-zod-query-coercion

NPM version NPM downloads CI Coverage

A Fastify plugin that automatically coerces query string parameters to match Zod schemas.

Install

npm install fastify-zod-query-coercion

Usage

import Fastify from 'fastify';
import { serializerCompiler, validatorCompiler, type FastifyZodOpenApiTypeProvider } from 'fastify-zod-openapi';
import fastifyZodQueryCoercion from 'fastify-zod-query-coercion';
import { z } from 'zod';

const fastify = Fastify().withTypeProvider<FastifyZodOpenApiTypeProvider>();

// Set up Zod validation
fastify.setValidatorCompiler(validatorCompiler);
fastify.setSerializerCompiler(serializerCompiler);

// Register the plugin
await fastify.register(fastifyZodQueryCoercion);

// Define a route with a Zod schema for query parameters
fastify.get('/example', {
  schema: {
    querystring: z.object({
      id: z.number(),
      name: z.string(),
      isActive: z.boolean(),
      tags: z.array(z.string()),
    }),
  },
  handler: (request, reply) => {
    const { id, name, isActive, tags } = request.query;
    console.log({
      id: typeof id, // 'number'
      name: typeof name, // 'string'
      isActive: typeof isActive, // 'boolean'
      tags: Array.isArray(tags), // true
    });
    reply.send({ id, name, isActive, tags });
  },
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) throw err;
  console.log('Server is running on http://localhost:3000');
  console.log('Try: http://localhost:3000/example?id=123&name=John&isActive=true&tags=a&tags=b');
});

How It Works

The plugin intercepts route definitions and transforms the Zod schemas for query parameters. It uses Zod's z.preprocess() to apply coercion rules similar to Ajv, ensuring that string inputs from query parameters are correctly converted to their intended types before Zod validation occurs.

Coercion Rules

This plugin follows Ajv coercion rules for Zod schemas. The coercion is applied before Zod validation occurs, ensuring that string inputs from query parameters are correctly converted to their intended types.

Currently Supported Coercion Rules

  1. Boolean:

    • String "true"true
    • String "false"false
  2. Number:

    • String representation of a number → Number (e.g., "123"123, "3.14"3.14)
  3. BigInt:

    • String representation of a bigint → BigInt (e.g., "123"123n)
  4. String:

    • Any string value → Remains unchanged
  5. Date:

    • String representation of a number or ISO date → Date (e.g., "2023-10-01T00:00:00.000Z"new Date("2023-10-01T00:00:00.000Z"))
  6. Null:

    • String "null"null
  7. Array:

    • Single non-array value → Array with that single value (e.g., "foo"["foo"])
  8. Tuple:

    • Single non-array value → Tuple with that single value (e.g., "foo"["foo"])
  9. Set:

    • Single non-array value → Set with that single value (e.g., "foo"new Set(["foo"]))
    • Array → Set with array values (e.g., ["foo", "bar"]new Set(["foo", "bar"]))

These coercion rules are applied recursively to nested schemas, including those within unions, optionals, and other complex types.

For a comprehensive list of supported Zod types, detailed coercion rules, and information about unsupported types, please refer to COERCION_RULES.md.

Route Parameters Support

By default, only query string parameters are processed. This plugin supports coercing both query string and route parameters. To enable route parameter coercion, include "params" in the coerceTypes option when registering the plugin.

// Register the plugin with route parameter coercion
await fastify.register(fastifyZodQueryCoercion, {
  coerceTypes: ['querystring', 'params']
});

// Define a route with a Zod schema for route parameters
fastify.get('/users/:userId', {
  schema: {
    params: z.object({
      userId: z.number(),
    }),
    querystring: z.object({
      isActive: z.boolean(),
    }),
  },
  handler: (request, reply) => {
    const { userId } = request.params;
    const { isActive } = request.query;
    console.log({
      userId: typeof userId, // 'number'
      isActive: typeof isActive, // 'boolean'
    });
    reply.send({ userId, isActive });
  },
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) throw err;
  console.log('Server is running on http://localhost:3000');
  console.log('Try: http://localhost:3000/users/123?isActive=true');
});

API Reference

fastifyZodQueryCoercion

The main plugin function. Register it with your Fastify instance:

fastify.register(fastifyZodQueryCoercion);

Options

coerceTypes (optional, default: ['querystring'])

Accepts an array of strings specifying which parts of the request should have coercion applied. Valid values are "querystring", "params", "headers", and "body".

Compatibility

This plugin is compatible with Fastify v4.x and v5.x.

Contributing

Contributions, issues, and feature requests are welcome!

License

This project is licensed under the MIT License.