UNPKG

9.69 kBMarkdownView Raw
1<p align="center">
2 <a href="#"><img src="./docs/images/banner.png" /></a>
3</p>
4
5<p align="center">
6 A simple and composable way <br/>
7 to validate data in JavaScript (and TypeScript).
8</p>
9<br/>
10<br/>
11
12<p align="center">
13 <a href="#usage">Usage</a>
14 <a href="#why">Why?</a>
15 <a href="#principles">Principles</a>
16 <a href="#demo">Demo</a>
17 <a href="#examples">Examples</a>
18 <a href="#documentation">Documentation</a>
19</p>
20
21<p align="center">
22 <a href="https://unpkg.com/superstruct/umd/superstruct.min.js">
23 <img src="https://badgen.net/bundlephobia/minzip/superstruct?color=green&label=size">
24 </a>
25 <a href="./package.json">
26 <img src="https://badgen.net/npm/v/superstruct?color=blue&label=version">
27 </a>
28</p>
29
30<br/>
31<br/>
32
33Superstruct makes it easy to define interfaces and then validate JavaScript data against them. Its type annotation API was inspired by [Typescript](https://www.typescriptlang.org/docs/handbook/basic-types.html), [Flow](https://flow.org/en/docs/types/), [Go](https://gobyexample.com/structs), and [GraphQL](http://graphql.org/learn/schema/), giving it a familiar and easy to understand API.
34
35But Superstruct is designed for validating data at runtime, so it throws (or returns) detailed runtime errors for you or your end users. This is especially useful in situations like accepting arbitrary input in a REST or GraphQL API. But it can even be used to validate internal data structures at runtime when needed.
36
37<br/>
38
39### Usage
40
41Superstruct allows you to define the shape of data you want to validate:
42
43```js
44import { assert, object, number, string, array } from 'superstruct'
45
46const Article = object({
47 id: number(),
48 title: string(),
49 tags: array(string()),
50 author: object({
51 id: number(),
52 }),
53})
54
55const data = {
56 id: 34,
57 title: 'Hello World',
58 tags: ['news', 'features'],
59 author: {
60 id: 1,
61 },
62}
63
64assert(data, Article)
65// This will throw an error when the data is invalid.
66// If you'd rather not throw, you can use `is()` or `validate()`.
67```
68
69Superstruct ships with validators for all the common JavaScript data types, and you can define custom ones too:
70
71```js
72import { is, struct, object, string } from 'superstruct'
73import isUuid from 'is-uuid'
74import isEmail from 'is-email'
75
76const Email = define('Email', isEmail)
77const Uuid = define('Uuid', isUuid.v4)
78
79const User = object({
80 id: Uuid,
81 email: Email,
82 name: string(),
83})
84
85const data = {
86 id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
87 email: 'jane@example.com',
88 name: 'Jane',
89}
90
91if (is(data, User)) {
92 // Your data is guaranteed to be valid in this block.
93}
94```
95
96Superstruct can also handle coercion of your data before validating it, for example to mix in default values:
97
98```ts
99import { create, object, number, string, defaulted } from 'superstruct'
100
101const User = object({
102 id: defaulted(number(), () => i++),
103 name: string(),
104})
105
106const data = {
107 name: 'Jane',
108}
109
110// You can apply the defaults to your data while validating.
111const user = create(data, User)
112// {
113// id: 1,
114// name: 'Jane',
115// }
116```
117
118And if you use TypeScript, Superstruct automatically ensures that your data has proper typings whenever you validate it:
119
120```ts
121import { is, object, number, string } from 'superstruct'
122
123const User = object({
124 id: number(),
125 name: string()
126})
127
128const data: unknown = { ... }
129
130if (is(data, User)) {
131 // TypeScript knows the shape of `data` here, so it is safe to access
132 // properties like `data.id` and `data.name`.
133}
134```
135
136Superstruct supports more complex use cases too like defining arrays or nested objects, composing structs inside each other, returning errors instead of throwing them, and more! For more information read the full [Documentation](#documentation).
137
138<br/>
139
140### Why?
141
142There are lots of existing validation libraries—[`joi`](https://github.com/hapijs/joi), [`express-validator`](https://github.com/ctavan/express-validator), [`validator.js`](https://github.com/chriso/validator.js), [`yup`](https://github.com/jquense/yup), [`ajv`](https://github.com/epoberezkin/ajv), [`is-my-json-valid`](https://github.com/mafintosh/is-my-json-valid)... But they exhibit many issues that lead to your codebase becoming hard to maintain...
143
144- **They don't expose detailed errors.** Many validators simply return string-only errors or booleans without any details as to why, making it difficult to customize the errors to be helpful for end-users.
145
146- **They make custom types hard.** Many validators ship with built-in types like emails, URLs, UUIDs, etc. with no way to know what they check for, and complicated APIs for defining new types.
147
148- **They don't encourage single sources of truth.** Many existing APIs encourage re-defining custom data types over and over, with the source of truth being spread out across your entire code base.
149
150- **They don't throw errors.** Many don't actually throw the errors, forcing you to wrap everywhere. Although helpful in the days of callbacks, not using `throw` in modern JavaScript makes code much more complex.
151
152- **They don't pre-compile schemas.** Many validators define schemas as plain JavaScript objects, which means they delegate the parsing of the schema logic to validation time, making them much slower.
153
154- **They're tightly coupled to other concerns.** Many validators are tightly coupled to Express or other frameworks, which results in one-off, confusing code that isn't reusable across your code base.
155
156- **They use JSON Schema.** Don't get me wrong, JSON Schema _can_ be useful. But it's kind of like HATEOAS—it's usually way more complexity than you need and you aren't using any of its benefits. (Sorry, I said it.)
157
158Of course, not every validation library suffers from all of these issues, but most of them exhibit at least one. If you've run into this problem before, you might like Superstruct.
159
160Which brings me to how Superstruct solves these issues...
161
162<br/>
163
164### Principles
165
1661. **Customizable types.** Superstruct's power is in making it easy to define an entire set of custom data types that are specific to your application, and defined in a _single_ place, so you have full control over your requirements.
167
1682. **Unopinionated defaults.** Superstruct ships with native JavaScript types, and everything else is customizable, so you never have to fight to override decisions made by "core" that differ from your application's needs.
169
1703. **Composable interfaces.** Superstruct interfaces are composable, so you can break down commonly-repeated pieces of data into components, and compose them to build up the more complex objects.
171
1724. **Useful errors.** The errors that Superstruct throws contain all the information you need to convert them into your own application-specific errors easy, which means more helpful errors for your end users!
173
1745. **Familiar API.** The Superstruct API was heavily inspired by [Typescript](https://www.typescriptlang.org/docs/handbook/basic-types.html), [Flow](https://flow.org/en/docs/types/), [Go](https://gobyexample.com/structs), and [GraphQL](http://graphql.org/learn/schema/). If you're familiar with any of those, then its schema definition API will feel very natural to use, so you can get started quickly.
175
176<br/>
177
178### Demo
179
180Try out the [live demo on JSFiddle](https://jsfiddle.net/85nse1mk/) to get an idea for how the API works, or to quickly verify your use case:
181
182[![Demo screenshot.](./docs/images/demo-screenshot.png)](https://jsfiddle.net/85nse1mk/)
183
184<br/>
185
186### Examples
187
188Superstruct's API is very flexible, allowing it to be used for a variety of use cases on your servers and in the browser. Here are a few examples of common patterns...
189
190- [Basic Validation](./examples/basic-validation.js)
191- [Custom Types](./examples/custom-types.js)
192- [Default Values](./examples/default-values.js)
193- [Optional Values](./examples/optional-values.js)
194- [Composing Structs](./examples/composing-structs.js)
195- [Throwing Errors](./examples/throwing-errors.js)
196- [Returning Errors](./examples/returning-errors.js)
197- [Testing Values](./examples/testing-values.js)
198- [Custom Errors](./examples/custom-errors.js)
199
200<br/>
201
202### Documentation
203
204Read the getting started guide to familiarize yourself with how Superstruct works. After that, check out the full API reference for more detailed information about structs, types and errors...
205
206- [**Guide**](https://docs.superstructjs.org/guides/01-getting-started)
207 - [Getting Started](https://docs.superstructjs.org/guides/01-getting-started)
208 - [Validating Data](https://docs.superstructjs.org/guides/02-validating-data)
209 - [Coercing Data](https://docs.superstructjs.org/guides/03-coercing-data)
210 - [Refining Validation](https://docs.superstructjs.org/guides/04-refining-validation)
211 - [Handling Errors](https://docs.superstructjs.org/guides/05-handling-errors)
212 - [Using TypeScript](https://docs.superstructjs.org/guides/06-using-typescript)
213- [**Reference**](https://docs.superstructjs.org/api-reference/core)
214 - [Core](https://docs.superstructjs.org/api-reference/core)
215 - [Types](https://docs.superstructjs.org/api-reference/types)
216 - [Refinements](https://docs.superstructjs.org/api-reference/refinements)
217 - [Coercions](https://docs.superstructjs.org/api-reference/coercions)
218 - [Utilities](https://docs.superstructjs.org/api-reference/utilities)
219 - [Errors](https://docs.superstructjs.org/api-reference/errors)
220 - [TypeScript](https://docs.superstructjs.org/api-reference/typescript)
221- [**FAQ**](https://docs.superstructjs.org/resources/faq)
222- [**Resources**](https://docs.superstructjs.org/resources/links)
223
224[![Docs screenshot.](./docs/images/docs-screenshot.png)](https://docs.superstructjs.org)
225
226<br/>
227
228### License
229
230This package is [MIT-licensed](./License.md).