@ cypress/schema- 工具

验证、消毒和文档 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是计划的名称,比如PersonschemaVersion版本喜欢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
许可证
本项目的许可条件如下: 麻省理工学院许可证。 。 。 .