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
npm i -S unhoaxGetting 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.
import { x } from 'unhoax'
interface User {
id: number
name: string
email: string
}
const userSchema = x.typed<User>().object({
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,
SomeLongInternalsAfterYourEntityType
>Inference
import { x } from 'unhoax'
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
const userSchema: x.ObjectSchema<{
id: number;
name: string;
email: string;
}, SomeLongInternalsAfterYourEntityType>Custom Types
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.
import { x } from 'unhoax'
x.array.defaultMaxSize // 500
x.Set.defaultMaxSize // 500
x.Map.defaultMaxSize // 500
x.string.defaultMaxSize // 500Those safety nts are not retro-active, you should define them at the entry-point of your program.
// You can define your own global guards:
x.array.defaultMaxSize = 3
// every array schema with no specific max size
// will now have a maximum of 3 items.
const mySchema = x.array(x.number)
mySchema.parse([1, 2, 3, 4]).success === falseYou can deactivate those guards by providing the value Infinity:
x.array.defaultMaxSize = InfinityUse unhoax with other tools
Leveraging the Standard Schema compliance:
Or any JSON Schema compatibility:
import { x, toJSONSchema } from 'unhoax'
const mySchema = x.object({ … }) // or x.array(…), or x.number, …
const schema = toJsonSchema(mySchema)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