@cypress/schema-tools

中文文档
4.7.10发布于 2023/04/13MITTypeScriptCommonJS近 30 天下载 8.2万

验证、消毒和记录 JSON 计划

此软件包已被标记为弃用

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

中文使用文档
文档目录20 节
  1. 动机
  2. 技选
  3. 示马斯
  4. 格式
  5. API 密码
  6. 有计划
  7. 文档计划
  8. 验证
  9. 断言计划
  10. 修饰
  11. 填满
  12. 净化
  13. 绑定
  14. 斯克马厄尔
  15. 添加财产
  16. 扩展
  17. 内存
  18. 调试
  19. 测试
  20. 许可证

@ cypress/schema- 工具 CircleCI renovate-app badge

验证、消毒和文档 JSON 计划

动机

明确 JSON 计划 描述在系统里传递的物体是好的!

  • 他们是一个活的可测试文档,而不是人工Wiki编辑
  • 为测试和整合提供实例
  • 验证API呼吁的投入和产出

技选

示马斯

每个单个计划对象应有3个部分:版本、实例和 JSON 计划 描述其属性。 见 试验/示范计划。从单一开始 ObjectSchema 描述一个对象的特定版本

import { ObjectSchema } from '@cypress/schema-tools'
const person100: ObjectSchema = {
  // has semantic version numbers
  version: {
    major: 1,
    minor: 0,
    patch: 0,
  },
  // JSON schema
  schema: {
    type: 'object',
    title: 'Person',
    description: 'An example schema describing a person',
    properties: {
      name: {
        type: 'string',
        format: 'name',
        description: 'this person needs a name',
      },
      age: {
        type: 'integer',
        minimum: 0,
        description: 'Age in years',
      },
    },
    required: ['name', 'age'],
    // note: you can just use required: true to require all properties
  },
  // has typical example
  example: {
    name: 'Joe',
    age: 10,
  },
}

您可以有多个独立的版本的"Person" schema,然后将它们组合成单个对象.

import {ObjectSchema, VersionedSchema, versionSchemas} from '@cypress/schema-tools'
const person100: ObjectSchema = { ... }
// maybe added another property
const person110: ObjectSchema = { ... }
// some big changes
const person200: ObjectSchema = { ... }
const personVersions: VersionedSchema = versionSchemas(person100, person110, person200)

最后,你大概有"Person"版本的"计划",也许还有"组织",也许还有其他的"计划". 所以把它们放入一个集合

import { SchemaCollection, combineSchemas } from '@cypress/schema-tools'
export const schemas: SchemaCollection = combineSchemas(
  personVersions,
  organizationVersions,
)

现在你可以使用 schemas 对象以验证和消毒任何对象.

格式

计外 包含有 JSON-schemas 的格式 可以定义用于验证值的自定义格式。 以单一自定义格式开始描述例如 UUID

// single custom format
import { CustomFormat, CustomFormats } from '@cypress/schema-tools'
const uuid: CustomFormat = {
  name: 'uuid', // the name
  description: 'GUID used through the system',
  // regular expression to use to validate value
  detect: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
  // (optional) replace actual value with this default value
  // when using to sanitize an object
  defaultValue: 'ffffffff-ffff-ffff-ffff-ffffffffffff',
}
// export all custom formats, in our case just 1
export const formats: CustomFormats = { uuid }

现在,每当你使用你的计划时,也通过这些格式,这样验证器就能知道如何从自定义格式中检查值.

// example JSON schema using uuid custom format
const employee100: ObjectSchema = {
  // has semantic version numbers
  version: {
    major: 1,
    minor: 0,
    patch: 0,
  },
  // JSON schema
  schema: {
    type: 'object',
    title: 'Employee',
    properties: {
      id: {
        type: 'string',
        format: 'uuid',
      },
    },
  },
  example: {
    id: 'a368dbfd-08e4-4698-b9a3-b2b660a11835',
  },
}
// employee100 goes into "schemas", then
assertSchema(schemas, formats)('Employee', '1.0.0')(someObject)

API 密码

有计划

回返 true 如果给定的策略存在于收藏中。 Curried 函数 .

import { hasSchema } from '@cypress/schema-tools'
import { schemas } from './schemas'
hasSchema(schemas, 'Name', '1.0.0') // true
hasSchema(schemas)('FooBarBaz')('1.0.0') // false

文档计划

您可以使用提供的方法记录您的计划。 示例代码文件

import { documentSchemas } from '@cypress/schema-tools'
import { schemas } from './schemas'
import { formats } from './formats'
console.log(documentSchemas(schemas, formats))

从国家防范机制的剧本中调用

{
  "scripts": {
    "document": "ts-node ./document.ts > schemas.md"
  },
  "devDependencies": {
    "ts-node": "5.0.1",
    "typescript": "2.8.1"
  }
}

如果您想要告诉一个方案来自何处, 您可以设置软件包名称, 这将在输出 Markdown 中添加一个注释

import { setPackageName, documentSchemas } from '@cypress/schema-tools'
import { schemas } from './schemas'
setPackageName(schemas, 'my-schemas')
console.log(documentSchemas(schemas, formats))
// each schema will have a note that it was defined in "my-schemas"

验证

对照一个方案检查给定对象,如果对象没有通过方案,则返回错误列表。 回返 true 如果对象通过方案,如果出现错误,则列出字符串(我知道,我们应该使用 任一或验证) (中文(简体) ).

import { validate } from '@cypress/schema-tools'
// see example in ./test/example-schemas.ts
import { schemas } from './my-schemas'
import { formats } from './my-formats'
const validatePerson100 = validate(schemas, formats)('person', '1.0.0')
const result = validatePerson100(someObject)
if (result === true) {
  // all good
} else {
  const errorMessage = result.join('\n')
  console.error(errorMessage)
}

典型的验证信件是

data.createdAt is required
data.createdAt must be date-time format

要在发现初始错误后停止, 请通过 greedy = false 旗帜

const validatePerson100 = validate(schemas, formats, false)('person', '1.0.0')

断言计划

对照方案(和格式)检查给定对象,并扔出一个 斯克马厄尔 如果对象违反了给定的策略.

try {
  assertSchema(schemas, formats)('Person', '1.0.0')(object)
} catch (e) {
  console.error(e.message)
  // can also inspect individual fields, see SchemaError
}

您可以从示例对象中替换一些字段来帮助动态数据。 例如,避免在无效时断开 id 值,我们可以看到 assertSchema 用于 id 来自示例对象的值.

const o = {
  name: 'Mary',
  age: -1,
}
assertSchema(schemas, formats)('Person', '1.0.0', {
  substitutions: ['age'],
})(o)
// everything is good, because the actual object asserted was
// {name: 'Mary', age: 10}

也可以限制错误消息并省略一些属性. 通常情况下,错误消息包含错误列表、当前和示例对象,这可能会形成一堵文字墙。 省略 object 财务报告和审定财务报表 example 生成错误消息时留下其他字段

const o = {
  name: 'Mary',
  age: -1,
}
assertSchema(schemas, formats)('Person', '1.0.0', {
  omit: {
    object: true,
    example: true,
  },
})(o)
// Error message is much much shorter, only "errors" and label will be there

默认json计划检查是 贪心 但你可以通过一个选项来限制

assertSchema(schemas, formats)('Person', '1.0.0', { greedy: false })

修饰

通常你有一个对象 更多 属性比计划允许的属性。 例如,如果你有了新的结果,应该给“老人”客户,你可能想 trim 以结果对象为对象,然后确定方案.

import { trim } from '@cypress/schema-tools'
const trimPerson = trim(schemas, 'Person', '1.0.0')
const person = ... // some result with lots of properties
const trimmed = trimPerson(person)
// trimmed should be valid Person 1.0.0 object
// if the values are actually matching [email protected]
// all extra properties should have been removed

填满

反之则 trim。尝试用图中明确的默认值填充缺失对象属性。 见 试验/填充试验.ts 举个例子.

净化

如果Schema有动态数据,比如时间戳或uuids,那么如果不先删除一些字段,打破了schema,就不可能比较对象. 要解决这个问题,您可以用格式标记一些属性,如果格式有默认值,您可以用默认值取代所有动态值.

下面的例子 name 属性已调用格式 name 像这样

name: {
  type: 'string',
  format: 'name'
}

现在我们可以消毒 任何可以替换的物体 name 值为默认值,但将保持其他属性不变.

import { sanitize, getDefaults } from '@cypress/schema-tools'
const name: CustomFormat = {
  name: 'name',
  description: 'Custom name format',
  detect: /^[A-Z][a-z]+$/,
  defaultValue: 'Buddy',
}
const exampleFormats: CustomFormats = {
  name,
}
const formatDefaults = getDefaults(exampleFormats)
const object = {
  name: 'joe',
  age: 21,
}
const sanitizePerson = sanitize(schemas, formatDefaults)('person', '1.0.0')
// now pass any object with dynamic "name" property
const result = sanitizePerson(object)
// result is {name: 'Buddy', age: 21}

另一个例子见 测试/卫生化-测试.ts

绑定

有多种方法可以验证,断言或消毒一个物体对一个计划. 都采用计划和(可选)格式。 但是,一个使用schema工具的项目可能有一个单集的schemas,它想一次又一次地使用. 这个 bind 方法使每个函数中的第一个参数容易被绑定在一个 schema 集合上,而只是使用一个对象的调用方法.

import { schemas } from './my-schemas'
import { formats } from './my-formats'
import { bind } from '@cypress/schema-tools'
const api = bind({ schemas, formats })
api.assertSchema('name', '1.0.0')(someObject)

见 测试/测试 实例

斯克马厄尔

当对一个方案主张对象时,会抛出一个自定义错误。 这是一个实例 Error,有一个非常详细的信息。 它还拥有额外的属性.

  • errors 是带有单个验证错误的字符串列表
  • object 正在验证的对象
  • example 策略的示例对象
  • schemaName 是计划的名称,比如 Person
  • schemaVersion 版本喜欢 1.0.0 如果知道的话 计划被破坏.

添加财产

您可以使用包含的内容轻松扩展已有的策略 addProperty 函数。 见 斜弧/动作 财务报告和审定财务报表 测试/附加财产测试 用于实例.

扩展

而不是一次添加一个属性,你可以简单地使用 extend(existingSchema, newSchemaObj)。 。 。 .

这个 existingSchema 将会被深克隆 并拥有 newSchemaObj 属性合并入.

若为 newSchemaObj.version 未提供,然后是前一个计划 minor 财产将被撞倒.

字段类 required 自动结合.

见 斜弧/动作 财务报告和审定财务报表 测试/扩展-schema-test.ts 用于实例.

内存

创建正则表达式只匹配给定字符串的一点工具功能 .

import { oneOfRegex } from '@cypress/schema-tools'
const r = oneOfRegex('foo', 'bar')
r.test('foo') // true
r.test('bar') // true
r.toString() // "/^(foo|bar)$/"

调试

要查看此模块中的日志消息, 请运行 DEBUG=schema-tools

测试

用途 ava - ts (韩语) 以直接对照 TypeScript 测试文件运行 Ava 测试跑取器。 使用 npm t 建造和测试所有的东西 test 文件夹.

要运行单个测试文件, 请使用命令

npx ava-ts test/<file-name.ts>

更新快照并使用动词报告器(打印测试名称)

npx ava-ts test/<file-name.ts> --verbose -u

许可证

本项目的许可条件如下: 麻省理工学院许可证。 。 。 .

版本与发布记录

@cypress/schema-tools 共发布 65 个版本,首次发布于 2018/04/18;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.7.10latest2023/04/133 年前
4.7.92021/12/014 年前
4.7.82021/07/045 年前
4.7.72020/11/195 年前
4.7.62020/11/195 年前
4.7.52020/09/196 年前

关于 @cypress/schema-tools 的常见问题

@cypress/schema-tools 是什么?

验证、消毒和记录 JSON 计划注意:该包已被作者标记为弃用——Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

如何安装 @cypress/schema-tools?

在项目目录运行 npm install @cypress/schema-tools,或使用 pnpm add / yarn add / bun add。

@cypress/schema-tools 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cypress/schema-tools 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@cypress/schema-tools 可以商用吗?

@cypress/schema-tools 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cypress/schema-tools 的下载量有多少?

根据 npm 官方下载统计,@cypress/schema-tools 在 2026/10/11 – 2026/11/09 这 30 天内被下载 81,826 次,日均约 2,728 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cypress/schema-tools 还在维护吗?

最新版本 4.7.10 发布于 2023/04/13(3 年前);至今共发布 65 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/04/18。作者已将其标记为弃用,新项目建议寻找替代方案。