Redocly/openapi-sampler
GitHub: Redocly/openapi-sampler
智能解析 OpenAPI 或 JSON Schema 并自动生成确定性示例数据的 JavaScript 库。
Stars: 219 | Forks: 51
# openapi-sampler
[](https://travis-ci.org/Redocly/openapi-sampler) [](https://coveralls.io/github/Redocly/openapi-sampler?branch=master) [](https://david-dm.org/Redocly/openapi-sampler) [](https://david-dm.org/Redocly/openapi-sampler#info=devDependencies)
基于 OpenAPI 负载/响应 schema 生成样本的工具
## 功能
- 确定性(给定特定输入,总是产生相同的输出)
- 支持复合关键字:`allOf`、`oneOf`、`anyOf`、`if/then/else`
- 通过 [`x-additionalPropertiesName`](https://github.com/Redocly/redoc/blob/master/docs/redoc-vendor-extensions.md#x-additionalpropertiesname) 支持 `additionalProperties`
- 尽可能使用 `const`、`examples`、`enum` 和 `default` —— 按此顺序
- 良好的数组支持:支持 `contains`、`minItems`、`maxItems` 和元组(`items` 作为数组)
- 支持 `minLength`、`maxLength`、`min`、`max`、`exclusiveMinimum`、`exclusiveMaximum`、([有限](https://fakerjs.dev/api/helpers.html#fromregexp)) `pattern`
- 支持以下 `string` 格式:
- email
- idn-email
- password
- date-time
- date
- time
- ipv4
- ipv6
- hostname
- idn-hostname
- uri
- uri-reference
- uri-template
- iri
- iri-reference
- uuid
- json-pointer
- relative-json-pointer
- regex
- 自动推断 schema 类型,遵循与 [json-schema-faker](https://www.npmjs.com/package/json-schema-faker#inferred-types) 相同的规则
- 支持 `$ref` 解析
- 对 JSON Schema draft 7 有基本支持(感谢 [@stoplightio](https://github.com/stoplightio) 的 [@P0lip](https://github.com/P0lip) 贡献)
## 安装
使用 [npm](https://docs.npmjs.com/getting-started/what-is-npm) 安装
```
npm install openapi-sampler
```
或者使用 [yarn](https://yarnpkg.com)
```
yarn add openapi-sampler
```
然后在代码中引用它:
```
var OpenAPISampler = require('openapi-sampler');
```
## 用法
#### `OpenAPISampler.sample(schema, [options], [spec])`
- **schema** (_必需_) - `object`
一个 [OpenAPI Schema Object](http://swagger.io/specification/#schemaObject) 或 JSON Schema Draft 7 文档。
- **options** (_可选_) - `object`
可用选项:
- **skipNonRequired** - `boolean`
不包含未在 [schema object 的 `required` 属性](https://swagger.io/docs/specification/data-models/data-types/#required)中指定的非必需对象属性
- **skipReadOnly** - `boolean`
不包含 `readOnly` 对象属性
- **skipWriteOnly** - `boolean`
不包含 `writeOnly` 对象属性
- **quiet** - `boolean`
不输出控制台警告消息
- **spec** - schema 所属的完整规范。仅当 schema 可能包含 `$ref` 时才需要。**spec** 不得包含任何外部引用
## 示例
```
const OpenAPISampler = require('.');
OpenAPISampler.sample({
type: 'object',
properties: {
a: {type: 'integer', minimum: 10},
b: {type: 'string', format: 'password', minLength: 10},
c: {type: 'boolean', readOnly: true}
}
}, {skipReadOnly: true});
// { a: 10, b: 'pa$$word_q' }
```
标签:API开发, API文档, Deterministic, GNU通用公共许可证, JSON Schema, MITM代理, Node.js, OpenAPI, Payload生成, Schema解析, Swagger, 前端工具, 接口测试, 数据Mock, 数据伪造, 数据可视化, 示例数据生成, 自定义脚本