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

zod-web-api

v0.1.4

Published

Zod Web API simplifies the process of integrating Zod with Web APIs including Request, URLSearchParams, and FormData.

Downloads

21

Readme

Basic usage

parseQueryAsync

Parses a query from a string URL, URLSearchParams, or Request object using a Zod schema.

import { z } from "zod";
import { parseQueryAsync } from "zod-web-api";

// create schema
const schema = z.object({
  username: z.string(),
  email: z.string().email(),
  age: z.number().int().min(18),
  newsletter: z.boolean()
});

// create URLSearchParams
const searchParams = new URLSearchParams();
searchParams.append("username", "john");
searchParams.append("email", "[email protected]");
searchParams.append("age", "23");
searchParams.append("newsletter", "false");

// parse
let submission = await parseQueryAsync(searchParams, schema);

// also accepts a string of the full URL
const url = `https://example.com?${searchParams}`;
submission = await parseQueryAsync(url, schema);

// also accepts a Request object
const request = new Request(url);
submission = await parseQueryAsync(request, schema);

// the three parseQueryAsync calls above would return this fully typed object
{
  username: "john",
  email: "john@example",
  age: 23,
  newsletter: false
}

parseFormDataAsync

Parses form data from a FormData or Request object using a Zod schema.

import { z } from "zod";
import { parseFormDataAsync } from "zod-web-api";

// create schema
const schema = z.object({
  username: z.string(),
  email: z.string().email(),
  age: z.number().int().min(18),
  hobbies: z.array(z.string()).min(1),
  newsletter: z.boolean()
});

// create FormData
const formData = new FormData();
formData.append("username", "john");
formData.append("email", "[email protected]");
formData.append("age", "23");
formData.append("hobbies", "programming");
formData.append("hobbies", "basketball");
formData.append("newsletter", "false");

// parse
let submission = await parseFormDataAsync(formData, schema);

// also accepts a Request object
const url = `https://example.com`;
const request = new Request(url, { method: "POST", body: formData });
submission = await parseFormDataAsync(request, schema);

// the two parseFormDataAsync calls above would return this fully typed object
{
  username: "john",
  email: "[email protected]",
  age: 23,
  hobbies: ["programming", "basketball"],
  newsletter: false
}

parseRequestAsync

Parses a Request's query and form data using a Zod schema. The query and form data are merged together before parsing.

import { z } from "zod";
import { parseRequestAsync } from "zod-web-api";

// create schema
const schema = z.object({
  username: z.string(),
  email: z.string().email(),
  q: z.string(),
});

// create URLSearchParams
const searchParams = new URLSearchParams();
searchParams.append("q", "photos");

// create FormData
const formData = new FormData();
formData.append("username", "john");
formData.append("email", "[email protected]");

// create Request
const request = new Request(`https://example.com?${searchParams}`, { method: "POST", body: formData });
const submission = await parseRequestAsync(request, schema);

// the parseRequestAsync call above would return this fully typed object
{
  username: "john",
  email: "[email protected]",
  q: "photos"
}

Nested Object and Array

Zod Web API support both nested object and array by leveraging a naming convention of the property name. Use the object.property and array[index] syntax to denote data structure. These notations could be combined for nested lists as well. e.g. tasks[0].label.

import { z } from "zod";
import { parseFormDataAsync } from "zod-web-api";
// create tasks schema
const taskSchema = z.object({
  label: z.string(),
  description: z.string()
});

// create schema
const schema = z.object({
  username: z.string(),
  tasks: taskSchema.array().min(2),
});

// create FormData
const formData = new FormData();
formData.append("username", "john");
formData.append("tasks[0].label", "Grocery Shopping");
formData.append("tasks[0].description", "Buy fruits/vegetables from grocery store.")
formData.append("tasks[1].label", "Email Management");
formData.append("tasks[1].description", "Organize and reply to urgent emails.")

// parse
let submission = await parseFormDataAsync(formData, schema);

// the parseFormDataAsync call above would return this fully typed object
{
  username: "john",
  tasks: [
    {
      label: "Grocery Shopping",
      description: "Buy fruits/vegetables from grocery store."
    },
    {
      label: "Email Management",
      description: "Organize and reply to urgent emails."
    }
  ]
}

Utilities

Zod Web API also comes with a couple utilities that help with common tasks

Transformer: findBy

Returns the first item with a property matching the passed value.

import { zt } from "zod-web-api";

const users = [
  { id: 1, name: "Christine" },
  { id: 2, name: "Danielle" },
  { id: 2, name: "Tom" },
];

const schema = z.string().transform(zt.findBy("name", users));
schema.parse("Tom"); // { id: 2, name: 'Tom' }

Transformer: json

Validates JSON encoded as a string, then returns the parsed value

import { zt } from "zod-web-api";

const schema = z.string().transform(zt.json(z.object({ name: z.string() })));
schema.parse('{"name": "John"}'); // { name: 'John' }

Credits

Zod Web API was heavily influenced by the following projects: