指定永远不应在 Swagger 或 OpenAPI 中发送的 属性
Specify property that should never be sent in Swagger or OpenAPI
我想指定永远不应从端点发送的字段。例如,假设我想确保没有端点响应 user.passwordHash
.
在 OpenAPI 中是否有与 additionalProperties: false
或 required: true
相反的东西?
您可以将 属性 定义为字符串并将最大长度设置为零。没有什么特别说 additionalProperties: true, except for passwordHash
.
type: object
properties:
passwordHash:
type: string
format: password
maxLength: 0
或者,您可以在发送之前简单地遍历对象并删除不需要的 属性。例如:
function removeProperty(property, value) {
if (Array.isArray(value)) {
return value.map(item => removeProperty(property, item))
} else if (value && typeof value === 'object') {
const result = {}
Object.keys(value)
.forEach(key => {
if (key !== property) {
result[key] = removeProperty(property, value[key])
}
})
return result
} else {
return value
}
}
const object = {
x: {
y: {
z: 1,
secret: 'password'
}
}
}
const clean = removeProperty('secret', object)
console.log(clean) // => { x: { y: { z: 1 } } }
OpenAPI 3.0 正是为此目的提供了 writeOnly
关键字:
Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response.
所以只需将相应的属性标记为writeOnly: true
:
passwordHash:
type: string
writeOnly: true
对于相反的情况还有 readOnly
- 不应在请求中发送但可以在响应中发送的属性。 readOnly
存在于 OpenAPI 3.0 和 2.0 中。
我想指定永远不应从端点发送的字段。例如,假设我想确保没有端点响应 user.passwordHash
.
在 OpenAPI 中是否有与 additionalProperties: false
或 required: true
相反的东西?
您可以将 属性 定义为字符串并将最大长度设置为零。没有什么特别说 additionalProperties: true, except for passwordHash
.
type: object
properties:
passwordHash:
type: string
format: password
maxLength: 0
或者,您可以在发送之前简单地遍历对象并删除不需要的 属性。例如:
function removeProperty(property, value) {
if (Array.isArray(value)) {
return value.map(item => removeProperty(property, item))
} else if (value && typeof value === 'object') {
const result = {}
Object.keys(value)
.forEach(key => {
if (key !== property) {
result[key] = removeProperty(property, value[key])
}
})
return result
} else {
return value
}
}
const object = {
x: {
y: {
z: 1,
secret: 'password'
}
}
}
const clean = removeProperty('secret', object)
console.log(clean) // => { x: { y: { z: 1 } } }
OpenAPI 3.0 正是为此目的提供了 writeOnly
关键字:
Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response.
所以只需将相应的属性标记为writeOnly: true
:
passwordHash:
type: string
writeOnly: true
对于相反的情况还有 readOnly
- 不应在请求中发送但可以在响应中发送的属性。 readOnly
存在于 OpenAPI 3.0 和 2.0 中。