Superstruct - 验证 Javascript 中的数据的简单方式


MIT
跨平台
JavaScript

软件简介

Superstruct 是一个简单和可组合的方式来验证 Javascript 中的数据。它的类型注释 API 受 Typescript、Flow、Go 和
GraphQL 的启发,令用户有熟悉感且易于理解。

不过,Superstruct 是为在运行时验证数据而设计的,所以它会为最终用户抛出(或返回)详细的运行时错误。 这在类似于接受 REST 或 GraphQL
API 中的任意输入的情况下特别有用。它甚至可以用来在运行时验证内部数据结构。

Demo 演示

Usage

Superstruct 导出一个struct 工厂模式,以根据特定模式验证数据的结构:

import { struct } from 'superstruct'

const Article = struct({
  id: 'number',
  title: 'string',
  is_published: 'boolean?',
  tags: ['string'],
  author: {
    id: 'number',
  }
})

const data = {
  id: 34,
  title: 'Hello World',
  tags: ['news', 'features'],
  author: {
    id: 1,
  } 
}

const article = Article(data)

// This will throw when the data is invalid, and return the data otherwise.
// If you'd rather not throw, use `Struct.validate()` or `Struct.test()`.

它可以识别所有原生的 JavaScript 类型。 你也可以使用 superstruct export 来定义自己的自定义数据类型(根据应用需求)

import { superstruct } from 'superstruct'
import isUuid from 'is-uuid'
import isEmail from 'is-email'

const struct = superstruct({
  types: {
    uuid: value => isUuid.v4(value),
    email: value => isEmail(value) && value.length < 256,
  }
})

const User = struct({
  id: 'uuid',
  email: 'email',
  is_admin: 'boolean?',
})

const data = {
  id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
  email: 'jane@example.com',
}

const user = User(data)