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

typebox-validation-util

v1.0.6

Published

Validate data using typebox in a single line

Downloads

3

Readme

Installation

When using yarn: yarn add typebox-validation-util @sinclair/typebox@^0.32.31 or when using npm: npm i typebox-validation-util @sinclair/typebox@^0.32.31

Use Case

You want to validate unknown data in one of the fastest and most convenient ways. You are using the excellent typebox library and want to avoid any unnecessary boilerplate.

Features

typebox-validation-util implements convenient defaults for you so you don't have to do extra manual work. This package:

  • Gives you an easy and straight forward way to validate typebox data via the only exported function of this package validateData. 🌟
  • Adds commonly used string formats such as email or ipv4 to validate against. 🛠️
    • These would otherwise have to be added manually, see here for the issue. Check the formats.ts file for what is added.
    • If you want any other formats added, feel free to create an issue and a followup PR.
  • Yields best validation performance. 🚀
    • Fast validation is guaranteed by compiling the schema and validating data only against compiled schemas. The compiled schema is cached so that future validations don't have to repeat the compilation step.
    • To better understand the huge performance differences for compiled schemas, you can check out this benchmark. See '@sinclair/typebox-(just-in-time)' which e.g. is twice as fast as ajv when it comes to loose asertion.
  • Uses typical nodejs error handling by throwing an error if validating the data fails. ✅
    • The Error is a typical nodejs Error. It contains a message and stack with all required details for debugging the error in a readable manner.
    • By default typebox would return ValueError values after you specifically request them by calling a separate function after validating.

Examples

import { Type } from "@sinclair/typebox";
import { validateData } from "typebox-validation-util";

const LoginInputSchema = Type.Object({
  name: Type.String({ format: "email" }),
  password: Type.String({ minLength: 8 }),
});

const demo = () => {
  // this will pass without errors
  const invalidatedData = {
    name: "[email protected]",
    password: "12345678",
  } as unknown;
  const data = validateData(invalidatedData, LoginInputSchema);
  console.log("validated data successfully: ", JSON.stringify(data, null, 2));

  // this will throw an error
  const invalidatedData2 = {
    name: "test@example,org",
    password: "1234567",
  } as unknown;
  const data2 = validateData(invalidatedData2, LoginInputSchema);
  console.log("validated data successfully: ", JSON.stringify(data2, null, 2));
};

const main = () => {
  try {
    // any application code here
    demo();
  } catch (e) {
    // centralized error handling here
    if (e instanceof Error) {
      console.log("error message: ", JSON.stringify(e.message, null, 2));
      console.log("error stack: ", JSON.stringify(e.stack, null, 2));
    }
  }
};

main();

The output of the example program given above is the following:


validated data successfully:  {
  "name": "[email protected]",
  "password": "12345678"
}

error message:  "schema: {\"format\":\"email\",\"type\":\"string\"} msg: Expected string to match 'email' format path: /name value: \"test@example,org\". schema: {\"minLength\":8,\"type\":\"string\"} msg: Expected string length greater or equal to 8 path: /password value: \"1234567\""
error stack:  "Error: schema: {\"format\":\"email\",\"type\":\"string\"} msg: Expected string to match 'email' format path: /name value: \"test@example,org\". schema: {\"minLength\":8,\"type\":\"string\"} msg: Expected string length greater or equal to 8 path: /password value: \"1234567\"\n    at validateData (/home/xddq/... imagine rest of stack here

For more examples check out the examples folder.

DEV/CONTRIBUTOR NOTES

If you have an idea or want to help implement something, feel free to do so. Please always start by creating an issue to avoid any unnecessary work on either side.

Please always create tests for new features that are implemented. This will decrease mental overhead for reviewing and developing in the long run.

Code Coverage

| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | | ------------- | ------- | -------- | ------- | ------- | ----------------- | | All files | 100 | 100 | 100 | 100 | | formats.ts | 100 | 100 | 100 | 100 | | validation.ts | 100 | 100 | 100 | 100 |

Similar Projects

  • typebox-validators which adds some additional functionality to the validation but keeps the error handling similar to the approach of typebox.

Template Repo

Template for this repo was taken from here.