使用 Ajv 加载使用从 OpenAPI 描述内的
$ref
文件导入的 yaml
的架构时,我收到错误。
这是我的
yaml
文件:
openapi: 3.0.3
info:
title: Demo
version: 1.0.0
paths:
/carousel:
get:
responses:
"200":
description: Successful operation
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/test"
components:
schemas:
other:
type: object
properties:
component:
type: object
test:
type: object
properties:
slides:
type: array
items:
type: object
properties:
contents:
type: array
items:
anyOf:
- $ref: "#/components/schemas/other"
这是我的代码(JS + Vite)
import Ajv from 'ajv'
import YamlContent from '../Config/API.yaml'; //vite.config.js with package @modyfi/vite-plugin-yaml
const validate =
new Ajv({
schemas: YamlContent.components.schemas
}).
getSchema(YamlContent.components.schemas.test);
我也尝试过:
const validate =
new Ajv().
addSchema(YamlContent.components.schemas.other).
compile(YamlContent.components.schemas.test);
但它总是给出同样的错误。 我在这里缺少什么?谢谢。
没有理由将
anyOf
用于单个模式,只需将该模式作为参考传递即可
openapi: 3.0.3
info:
title: Demo
version: 1.0.0
paths:
/carousel:
get:
responses:
"200":
description: Successful operation
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/test"
components:
schemas:
other:
type: object
properties:
component:
type: object
test:
type: object
properties:
slides:
type: array
items:
type: object
properties:
contents:
type: array
items:
$ref: "#/components/schemas/other"
OpenAPI 3.0.x 需要使用
ajv-draft-04
和 ajv-formats
包。
因为您使用的是 yaml 文件,所以您需要一种方法来加载它
js-yaml
{
"dependencies": {
"ajv": "^8",
"ajv-draft-04": "^1.0.0",
"js-yaml": "^4.1.0",
"ajv-formats": "^2.1.1"
}
}
我们使用
strict:false
来确保 ajv 验证器正确遵守 JSON Schema 规范。
想法是使用
addSchema()
方法添加整个 OpenAPI 描述;然后使用 validate
函数,并为要在第一个参数中验证的组件模式提供带有 $ref
的对象模式,并将数据实例作为第二个参数传递。
然后输出结果。
const Ajv = require('ajv-draft-04')
const addFormats = require('ajv-formats')
const fs = require('fs')
const { load } = require('js-yaml')
const openapiDescription = load(fs.readFileSync('./Config/API.yaml'))
const testData = {
"slides": [
{
"contents":
[{ "component": {} }]
}]
}
try {
const ajv = new Ajv({ strict: false })
addFormats(ajv)
ajv.addSchema(openapiDescription, "API.yaml")
let validate = ajv.validate({ "$ref": "API.yaml#/components/schemas/test" }, testData)
console.log({
valid: validate,
error: ajv.errorsText(validate.errors)
})
}
catch (error) {
console.error(error.message)
}