UNPKG

9.22 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.
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://travis-ci.org/ianstormtaylor/superstruct">
23 <img src="https://travis-ci.org/ianstormtaylor/superstruct.svg?branch=master">
24 </a>
25 <a href="https://unpkg.com/superstruct/umd/superstruct.min.js">
26 <img src="http://img.badgesize.io/https://unpkg.com/superstruct/umd/superstruct.min.js?compression=gzip&amp;label=size&amp;maxAge=300">
27 </a>
28 <a href="./package.json">
29 <img src="https://img.shields.io/npm/v/superstruct.svg?maxAge=300&label=version&colorB=007ec6&maxAge=300">
30 </a>
31 <a href="./License.md">
32 <img src="https://img.shields.io/npm/l/slate.svg?maxAge=300">
33 </a>
34</p>
35
36<br/>
37<br/>
38
39Superstruct 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.
40
41But 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.
42
43<br/>
44
45### Usage
46
47Superstruct exports a `struct` factory for creating structs that can validate data against a specific schema:
48
49```js
50import { struct } from 'superstruct'
51
52const Article = struct({
53 id: 'number',
54 title: 'string',
55 is_published: 'boolean?',
56 tags: ['string'],
57 author: {
58 id: 'number',
59 },
60})
61
62const data = {
63 id: 34,
64 title: 'Hello World',
65 tags: ['news', 'features'],
66 author: {
67 id: 1,
68 },
69}
70
71const article = Article(data)
72
73// This will throw when the data is invalid, and return the data otherwise.
74// If you'd rather not throw, use `Struct.validate()` or `Struct.test()`.
75```
76
77It recognizes all the native JavaScript types out of the box. But you can also define your own custom data types—specific to your application's requirements—by using the `superstruct` export:
78
79```js
80import { superstruct } from 'superstruct'
81import isUuid from 'is-uuid'
82import isEmail from 'is-email'
83
84const struct = superstruct({
85 types: {
86 uuid: value => isUuid.v4(value),
87 email: value => isEmail(value) && value.length < 256,
88 },
89})
90
91const User = struct({
92 id: 'uuid',
93 email: 'email',
94 is_admin: 'boolean?',
95})
96
97const data = {
98 id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
99 email: 'jane@example.com',
100}
101
102const user = User(data)
103```
104
105Superstruct supports more complex use cases too like defining list or scalar structs, applying default values, composing structs inside each other, returning errors instead of throwing them, etc. For more information read the full [Documentation](#documentation).
106
107<br/>
108
109### Why?
110
111There 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...
112
113- **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.
114
115- **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.
116
117- **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.
118
119- **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.
120
121- **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.
122
123- **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.
124
125- **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.)
126
127Of 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.
128
129Which brings me to how Superstruct solves these issues...
130
131<br/>
132
133### Principles
134
1351. **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.
136
1372. **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.
138
1393. **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.
140
1414. **Terse schemas.** The schemas in Superstruct are designed to be extremely terse and expressive. This makes them very easy to read and write, encouraging you to have full data validation coverage.
142
1435. **Compiled validators.** Superstruct does the work of compiling its schemas up front, so that it doesn't spend time performing expensive tasks for every call to the validation functions in your hot code paths.
144
1456. **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!
146
1477. **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.
148
149<br/>
150
151### Demo
152
153Try out the [live demo on JSFiddle](https://jsfiddle.net/yjugaeg8/2/) to get an idea for how the API works, or to quickly verify your use case:
154
155[![Demo screenshot.](./docs/images/demo-screenshot.png)](https://jsfiddle.net/yjugaeg8/2/)
156
157<br/>
158
159### Examples
160
161Superstruct'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...
162
163- [Basic Validation](./examples/basic-validation.js)
164- [Custom Types](./examples/custom-types.js)
165- [Default Values](./examples/default-values.js)
166- [Optional Values](./examples/optional-values.js)
167- [Composing Structs](./examples/composing-structs.js)
168- [Throwing Errors](./examples/throwing-errors.js)
169- [Returning Errors](./examples/returning-errors.js)
170- [Custom Errors](./examples/custom-errors.js)
171
172<br/>
173
174### Documentation
175
176Read 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...
177
178- [**Guide**](./docs/guide.md)
179 - [Installing Superstruct](./docs/guide.md#installing-superstruct)
180 - [Creating Structs](./docs/guide.md#creating-structs)
181 - [Defining Custom Data Types](./docs/guide.md#defining-custom-data-types)
182 - [Setting Default Values](./docs/guide.md#setting-default-values)
183 - [Throwing Customized Errors](./docs/guide.md#throwing-customized-errors)
184 - [Validating Complex Shapes](./docs/guide.md#validating-complex-shapes)
185 - [Composing Structs](./docs/guide.md#composing-structs)
186- [**Reference**](https://superstructjs.org)
187 - [`Struct`](https://superstructjs.org/interfaces/struct)
188 - [`Superstruct`](https://superstructjs.org/interfaces/superstruct)
189 - [`Types`](https://superstructjs.org#types)
190 - [`StructError`](https://superstructjs.org/classes/structerror)
191 - [`isStruct`](https://superstructjs.org#isstruct)
192- [**Resources**](/docs/resources.md)
193
194<br/>
195
196### License
197
198This package is [MIT-licensed](./License.md).