type/data-centric schema library. A schema library empower you, not constrain you with their types messy types.
npm install unhoaxA 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.
---
``bash`
npm i -S unhoax
Check out the documentation website, you may want to start with the getting started guide 😊
This section only describes trivial how tos, see the reference for a list of available schemas and utilities.
`ts
import { x } from 'unhoax'
interface User {
id: number
name: string
email: string
}
const userSchema = x.typed
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
>
`ts
import { x } from 'unhoax'
const userSchema = x.object({
id: x.number,
name: x.string,
email: x.string,
})
type User = x.TypeOf
userSchema.parse({ … })
// { result: true, value: { id: number, … } } <- User is not properly named
const userSchema: x.ObjectSchema<{
id: number;
name: string;
email: string;
}, SomeLongInternalsAfterYourEntityType>
`
`ts
import { x } from 'unhoax'
type Email = …
declare function isEmail(value: string): value is Email
const emailSchema = x.string.guardAs('Email', isEmail) // Schema
`
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 // 500
x.Set.defaultMaxSize // 500
x.Map.defaultMaxSize // 500
x.string.defaultMaxSize // 500
`
Those safety nts are not retro-active, you should define them at the entry-point of your program.
`ts
// 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 === false
`
You can deactivate those guards by providing the value Infinity:
`ts`
x.array.defaultMaxSize = Infinity
with other toolsLeveraging the Standard Schema compliance:
Or any JSON Schema compatibility:
`ts
import { x, toJSONSchema } from 'unhoax'
const mySchema = x.object({ … }) // or x.array(…), or x.number, …
const schema = toJsonSchema(mySchema)
``
Visit unhoax-chance to see how to generate random fixtures from your schemas using ChanceJS.
See here