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

码农软件 · 软件分类 · 常用JavaScript包 · 2019-04-04 20:41:50

软件介绍

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)

本文地址:https://codercto.com/soft/d/2870.html

失控

失控

[美] 凯文·凯利 / 东西文库 / 新星出版社 / 2011-3 / 98.00元

2006年,《长尾理论》的作者克里斯·安德森在亚马逊网站上这样评价该书: “这可能是90年代最重要的一本书”,并且是“少有的一年比一年卖得好的书”。“尽管书中的一些例子在十几年后可能有些过时,但(它们所表达的)信息却越来越成为真知灼见”。“在那时人们还无法想象博客和维基等大众智慧的突起,但凯利却分毫不差地预见到了。这可能是过去十年来最聪明的一本书。” 这是《黑客帝国》主要演员的必读物之......一起来看看 《失控》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具