Skip to content

Package SizeTotal coverageDownloads

A Standard Schema-compliant library intended for data safety, leveraging concise & elegant types to prevent unreadable 100+ lines TypeScript error messages.

Following the unix mindset, unhoax proposes less features than other libraries, encouraging you to build your own custom schemas when relevant, ie: email schemas.


Installation

bash
npm i -S unhoax

Getting Started

Check out the documentation website, you may want to start with the getting started guide 😊

Basic Usage

This section only describes trivial how tos, see the reference for a list of available schemas and utilities.

ts
import { x } from 'unhoax'

// type-driven:
interface User {
  id: number
  name: string
  email: string
}

const userSchema = x.object<User>({
  id: x.number,
  name: x.string,
  email: x.string,
})
userSchema.parse({ … })
// { result: true, value: User } <- `User` is properly named via intellisense

// hovering on `userSchema` prompts this ; simple type, right?
const userSchema: x.ObjectSchema<User>

// infer-driven:
const userSchema = x.object({
  id: x.number,
  name: x.string,
  email: x.string,
})
type User = x.TypeOf<typeof userSchema>

userSchema.parse({ … })
// { result: true, value: { id: number, … } } <- `User` is not properly named

// hovering on `userSchema` prompts this ; simple type, right?
const userSchema: x.ObjectSchema<{
    id: number;
    name: string;
    email: string;
}>

Inference

ts
import { x } from 'unhoax'

const schema = x.object({ name: x.string })
type Test = x.TypeOf<typeof schema>
declare const test: Test // { name: string }

Custom Types

ts
import { x } from 'unhoax'

type Email =
declare function isEmail(value: string): value is Email

const emailSchema = x.string.guardAs('Email', isEmail) // Schema<Email>

Safety first

There are default size guards everywhere, to diminish the risk of Denial of Service attacks, resource exhaustion and oversized payload.

ts
import { x } from 'unhoax'

x.array.defaultMaxSize // 100
x.setOf.defaultMaxSize // 100
x.mapOf.defaultMaxSize // 100
x.string.defaultMaxSize // 100_000

// You can define your own guards:
x.array.defaultMaxSize = 10_000
// every array schema with no specific max size
// will now have a maximum of 10,000 items.

// The rules are retro-active:
const mySchema = x.array(x.number)

x.array.defaultMaxSize = 3
mySchema.parse([1, 2, 3, 4]).success === false

You can deactivate those guards by providing the value Infinity:

ts
x.array.defaultMaxSize = Infinity

Generating random fixtures from your schemas

Visit unhoax-chance to see how to generate random fixtures from your schemas using ChanceJS.

The purpose of this library – Why yet-another?

See here