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-get

v1.0.1

Published

**zod-get** is a **tiny** TypeScript library that provides a safe and convenient way to traverse and validate JSON-like structures using [Zod](https://github.com/colinhacks/zod) schemas. It allows you to safely navigate through nested objects with unknown

Downloads

4

Readme

zod-get

zod-get is a tiny TypeScript library that provides a safe and convenient way to traverse and validate JSON-like structures using Zod schemas. It allows you to safely navigate through nested objects with unknown structures and obtain values while ensuring the values conform to specified types.

Features

  • Safely traverse through nested objects in a JSON-like structure.
  • Validate values against Zod schemas.
  • Retrieve values from the structure while ensuring type safety.
  • Gracefully handle undefined or invalid properties.

Installation

You can install zod-get via npm:

npm install zod-get

Usage

  1. Import the get function:
import { get } from 'zod-get';
import * as z from 'zod';
  1. Safely traverse and validate the JSON-like structure:

const examplePayload = {
  "company": {
    "name": "TechCorp",
    "departments": {
      "marketing": {
        "team_lead": "Alice",
        "members": ["Bob", "Carol", "David"]
      },
    }
  }
};

// Traverse the tree without needing to validate every part
// (you will only need `?.` if noUncheckedIndexedAccess is enabled)
const teamLeadName = get(examplePayload)?.company?.departments?.marketing?.team_lead?.(z.string());

console.log(teamLeadName); // Output: "Alice"

// Oops, this doesn't exist, but we don't get any runtime error:
const doesntExist = get(examplePayload).company.departments.does_not_exist.team_lead(z.string());

console.log(doesntExist); // Output: undefined

// zod-get won't let you use a value without validating it:
const teamLead: string = get(examplePayload).company.departments.does_not_exist.team_lead;
                    // ^ TypeScript: Type 'Unvalidated' is not assignable to type 'string'.

Why

In Typescript, the unknown type is a helpful alternative to any, because it requires the developer to check the value before using it, but it can be cumbersome to use for deeply nested structures, since you can't use a common JS idiom:

// This is fine in JS, but if examplePayload is `unknown` in TS, you can't do this.
const isTeamLeadAlice = examplePayload?.company?.departments?.marketing?.team_lead === "Alice";  

One TypeScript alternative is to use any, but it could cause issues:

// Oops teamLead is supposed to be a string, but it's undefined.  Or maybe it's a number?  Who knows?
const teamLead: string = (examplePayload as any)?.company?.departments?.does_not_exist?.team_lead;  

So the safer alternative is to use a zod schema, which you should do most of the time if you care about type safety!

// Oof!
const schema = z.object({
  company: z.object({
    departments: z.object({
      marketing: z.object({
        team_lead: z.string(),
      }),
    }),
  }),
});

const parsed = schema.safeParse(examplePayload);
const teamLead: string | undefined = parsed.success
  ? parsed.data.company.departments.marketing.team_lead
  : undefined;

That works for most cases but sometimes it can be pretty verbose, especially for a one-off deep access like this.

API

get(data: unknown): Unvalidated

The get function returns an "Unvalidated" type for arbitrary, yet safe, navigation through a JSON-like structure. "JSON-like" refers to scalar data that is potentially nested. In other words, zod-get won't allow function calls and may not work with other odd scenarios. Though it should be possible to call a function if you validate it first.

  • data: The JSON-like structure to traverse.

Unvalidated

The Unvalidated type represents a arbitrarily-traversable type unassignable to non-unknown/any types. Calling an Unvalidated with a zod schema "unwraps" the value, validating it against the supplied schema. If it passes the underlying value at the property path is returned. Otherwise, undefined is returned.

Contributing

Contributions are welcome! Please feel free to open issues or submit pull requests to improve the library.

To install dependencies:

bun install

To run:

bun run index.ts

This project was created using bun init in bun v1.0.33. Bun is a fast all-in-one JavaScript runtime.

License

This project is licensed under the MIT License - see the LICENSE file for details.