验证 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://www.codercto.com/soft/d/2870.html

HTML 5实战

HTML 5实战

陶国荣 / 机械工业出版社 / 2011-11 / 59.00元

陶国荣编著的《HTML5实战》是一本系统而全面的HTML 5教程,根据HTML 5标准的最新草案,系统地对HTML 5的所有重要知识点进行了全面的讲解。在写作方式上,本书以一种开创性的方式使理论与实践达到极好的平衡,不仅对理论知识进行了清晰而透彻的阐述,而且根据读者理解这些知识的需要,精心设计了106个完整(每个案例分为功能描述、实现代码、效果展示和代码分析4个部分)的实战案例,旨在帮助读者通过实......一起来看看 《HTML 5实战》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器