UNPKG

9.07 kBMarkdownView Raw
1
2<p align="center">
3 <a href="#"><img src="./docs/images/banner.png" /></a>
4</p>
5
6<p align="center">
7 A simple and composable way <br/>
8 to validate data in JavaScript.
9</p>
10<br/>
11<br/>
12
13<p align="center">
14 <a href="#usage">Usage</a>
15 <a href="#why">Why?</a>
16 <a href="#principles">Principles</a>
17 <a href="#demo">Demo</a>
18 <a href="#examples">Examples</a>
19 <a href="#documentation">Documentation</a>
20</p>
21
22<p align="center">
23 <a href="https://travis-ci.org/ianstormtaylor/superstruct">
24 <img src="https://travis-ci.org/ianstormtaylor/superstruct.svg?branch=master">
25 </a>
26 <a href="https://unpkg.com/superstruct/umd/superstruct.min.js">
27 <img src="http://img.badgesize.io/https://unpkg.com/superstruct/umd/superstruct.min.js?compression=gzip&amp;label=size&amp;maxAge=300">
28 </a>
29 <a href="./packages/superstruct/package.json">
30 <img src="https://img.shields.io/npm/v/superstruct.svg?maxAge=300&label=version&colorB=007ec6&maxAge=300">
31 </a>
32 <a href="./License.md">
33 <img src="https://img.shields.io/npm/l/slate.svg?maxAge=300">
34 </a>
35</p>
36
37<br/>
38<br/>
39
40Superstruct 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.
41
42But 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.
43
44
45<br/>
46
47### Usage
48
49Superstruct exports a `struct` factory for creating structs that can validate data against a specific schema:
50
51```js
52import { struct } from 'superstruct'
53
54const Article = struct({
55 id: 'number',
56 title: 'string',
57 is_published: 'boolean?',
58 tags: ['string'],
59 author: {
60 id: 'number',
61 }
62})
63
64const data = {
65 id: 34,
66 title: 'Hello World',
67 tags: ['news', 'features'],
68 author: {
69 id: 1,
70 }
71}
72
73const article = Article(data)
74
75// This will throw when the data is invalid, and return the data otherwise.
76// If you'd rather not throw, use `Struct.validate()` or `Struct.test()`.
77```
78
79It 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:
80
81```js
82import { superstruct } from 'superstruct'
83import isUuid from 'is-uuid'
84import isEmail from 'is-email'
85
86const struct = superstruct({
87 types: {
88 uuid: value => isUuid.v4(value),
89 email: value => isEmail(value) && value.length < 256,
90 }
91})
92
93const User = struct({
94 id: 'uuid',
95 email: 'email',
96 is_admin: 'boolean?',
97})
98
99const data = {
100 id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
101 email: 'jane@example.com',
102}
103
104const user = User(data)
105```
106
107Superstruct 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).
108
109
110<br/>
111
112### Why?
113
114There 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...
115
116- **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.
117
118- **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.
119
120- **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.
121
122- **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.
123
124- **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.
125
126- **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.
127
128- **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.)
129
130Of 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.
131
132Which brings me to how Superstruct solves these issues...
133
134
135<br/>
136
137### Principles
138
1391. **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.
140
1412. **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.
142
1434. **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.
144
1455. **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.
146
1477. **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.
148
1496. **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!
150
1513. **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.
152
153
154<br/>
155
156### Demo
157
158Try 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:
159
160[![Demo screenshot.](./docs/images/demo-screenshot.png)](https://jsfiddle.net/yjugaeg8/2/)
161
162
163<br/>
164
165### Examples
166
167Superstruct'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...
168
169- [Basic Validation](./examples/basic-validation.js)
170- [Custom Types](./examples/custom-types.js)
171- [Default Values](./examples/default-values.js)
172- [Optional Values](./examples/optional-values.js)
173- [Composing Structs](./examples/composing-structs.js)
174- [Throwing Errors](./examples/throwing-errors.js)
175- [Returning Errors](./examples/returning-errors.js)
176- [Custom Errors](./examples/custom-errors.js)
177
178
179<br/>
180
181### Documentation
182
183Read 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...
184
185- [**Guide**](./docs/guide.md)
186 - [Installing Superstruct](./docs/guide.md#installing-superstruct)
187 - [Creating Structs](./docs/guide.md#creating-structs)
188 - [Defining Custom Data Types](./docs/guide.md#defining-custom-data-types)
189 - [Setting Default Values](./docs/guide.md#setting-default-values)
190 - [Throwing Customized Errors](./docs/guide.md#throwing-customized-errors)
191 - [Validating Complex Shapes](./docs/guide.md#validating-complex-shapes)
192 - [Composing Structs](./docs/guide.md#composing-structs)
193- [**Reference**](./docs/reference.md)
194 - [API](./docs/reference.md#api)
195 - [Structs](./docs/reference.md#structs)
196 - [Types](./docs/reference.md#types)
197 - [Errors](./docs/reference.md#errors)
198
199
200<br/>
201
202### License
203
204This package is [MIT-licensed](./License.md).