我的登录端点可以有“社交”登录和“用户”登录,因此正文可以如下所示:
user: {
email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1b5a4b2b581a6aca0a8adefa2aeac" rel="noreferrer noopener nofollow">[email protected]</a>',
password: 'test'
}
或者像这样:
authentication: {
provider: 'facebook',
token: 'abcd'
}
我想创建一个 JSON 架构来验证第一个正文或第二个正文。我偶然发现了 oneOf
,这就是我尝试过的:
body: {
oneOf: [{
properties: {
user: {
type: 'object',
required: [
'email',
'password'
],
email: {
type: 'string',
format: 'email'
},
password: {
type: 'string',
minLength: 6,
maxLength: 32
}
},
}
}, {
properties: {
authentication: {
type: 'object',
required: [
'provider',
'token'
],
provider: {
type: 'string',
enum: ['facebook']
},
token: {
type: 'string'
}
}
}
}]
}
但是这给了我以下错误:
{
"keyword": "oneOf",
"dataPath": ".body",
"schemaPath": "#/properties/body/oneOf",
"params": {},
"message": "should match exactly one schema in oneOf"
}
如果有人能帮我为此设置 JSON 架构,那就太棒了。谢谢
最佳答案
您可以使用oneOf
来做到这一点。尽管我会以不同的方式使用它。
{
"$schema": "http://json-schema.org/schema#",
"type": "object",
"properties": {
"login": {
"oneOf": [
{
"required": [
"user"
]
},
{
"required": [
"authentication"
]
}
],
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
},
"authentication": {
"type": "object",
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
}
}
}
}
}
这样,两个 json 就根据架构进行了验证
{
"login": {
"authentication": {
"provider": "facebook",
"token": "abcd"
}
}
}
{
"login": {
"user": {
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="790d1c0a0d391e14181015571a1614" rel="noreferrer noopener nofollow">[email protected]</a>",
"password": "test"
}
}
}
但是如果你尝试将它们放在一起,它将不会验证
{
"login": {
"authentication": {
"provider": "facebook",
"token": "abcd"
},
"user": {
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="225647515662454f434b4e0c414d4f" rel="noreferrer noopener nofollow">[email protected]</a>",
"password": "test
}
}
}
关于JSON 模式,oneOf 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45686206/