我们正在遵循一种设计优先的方法来创建API。
我们要使用继承的方案之一,我无法为其定义规范。
这是它的C#类型
public class PublishRequest
{
[JsonProperty("notificationType")]
public string NotificationType { get; set; }
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("timestamp")]
public string Timestamp { get; set; }
[JsonProperty("payload")]
public List<BaseObject> Payload { get; set; }
}
此类具有BaseObject的属性
public class BaseObject
{
[JsonProperty("Id")]
public string Id { get; set; }
}
所有其他类型都从该类型继承,如下所示:
public class Accounts:BaseObject
{
[JsonProperty("phone")]
public string Phone { get; set; }
[JsonProperty("accountid")]
public string AccountID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("legalname")]
public string LegalName { get; set; }
[JsonProperty("website")]
public string Website { get; set; }
[JsonProperty("linkedin")]
public string LinkedIn { get; set; }
[JsonProperty("twitter")]
public string Twitter { get; set; }
}
使用这些类的规范是这样的:
/notification/publish:
post:
summary: publish notification
tags:
- Notification
requestBody:
description: publish request body
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PublishRequest'
responses:
"200":
description: success message
我面临的问题是为其定义架构。
架构如下
PublishRequest:
required:
- notificationType
properties:
notificationType:
type: string
enum: [account_created, account_updated]
source:
type: string
enum: [A, B]
timestamp:
type: string
format: date-time
payload:
$ref: "#/components/schemas/NotificationPayload"
NotificationPayload:
type: array
items:
oneOf:
- $ref: "#/components/schemas/Account"
BaseObject:
properties:
Id:
type: string
Account:
allOf:
$ref: '#/components/schemas/BaseObject'
type: object
properties:
phone:
type: string
accountId:
type: string
name:
type: string
legalname:
type: string
website:
type: string
linkedin:
type: string
twitter:
type: string
facebook:
type: string
defaultcurrency:
type: string
我在招摇编辑器中不断出现此错误
Structural error at components.schemas.Account.allOf
should be array
答案 0 :(得分:0)
allOf
的正确语法如下。 allOf
包含子方案的列表,因此每个子方案必须在YAML中以-
为前缀。
Account:
allOf:
- $ref: '#/components/schemas/BaseObject'
- type: object
properties:
phone:
type: string
...
其他一些事情:
在NotificationPayload
中,items
不需要oneOf
,因为只有一个子模式。
NotificationPayload:
type: array
items:
$ref: "#/components/schemas/Account"
请记住将type: object
添加到对象模式,在此示例中-PublishRequest
和BaseObject
。仅仅使用properties
关键字还不足以指示对象类型,而schemas without type
实际上意味着“任何类型”。