,所以我正在从我的RAML规范中提取JSON模式,以验证获取方法中的输出,也可以在Post方法中的输入中提取JSON架构。
此类型的每个实体都有"必需" ID属性 - 至少在列出"获取项目"或'Get Collection'重新要求中的这些实体时,需要。但是,当验证接收到的邮政数据以创建这样的实体时,显然不需要ID(无论如何是发送的)。
获得该ID属性所需的最佳干燥方法是什么,但不是必需的,或者更好的是在邮政请求类型中不存在的最好的干燥方法?
tl; dr:开始阅读以下;)
示例使其更容易理解:
对于获取请求,类型应该是:
properties:
id:
something1:
something2?:
对于邮政请求,类型应为:
properties:
something1:
something2?:
无需单独定义两个,也不用使用继承才能为每个资源创建两种类型。
理想情况下,我会这样解决,但这似乎不起作用:
get:
description: Retrieve a list of <<resourcePathName|!uppercamelcase>>.
responses:
200:
body:
application/json:
type: [ entity_id_object, <<resourcePathName|!singularize|!uppercamelcase>> ][]
example: <<exampleCollection>>
和 entity_id_object
仅:
entity_id_object:
properties:
id:
我认为这是因为<<resourcePathName|!singularize|!uppercamelcase>>
在此组合中不起作用。
我想不出一种没有两种类型的方法。但是,这个示例至少只会使您仅通过一种类型,然后自动将" Noid"附加到邮政请求的类型名称中。
#%RAML 1.0
title: My API
version: v1
mediaType: application/json
types:
ResponseNoId:
properties:
something1:
something2?:
ResponseId:
properties:
id:
something1:
something2?:
Response:
ResponseNoId|ResponseId
resourceTypes:
collection:
usage: Use this resourceType to represent a collection of items
description: A collection of <<resourcePathName|!uppercamelcase>>
get:
description: |
Get all <<resourcePathName|!uppercamelcase>>,
optionally filtered
is: [ hasResponseCollection: { typeName: <<typeName>> } ]
post:
description: |
Create a new <<resourcePathName|!uppercamelcase|!singularize>>
is: [ hasRequestItem: { typeName: <<typeName>> } ]
item:
usage: Use this resourceType to represent any single item
description: A single <<typeName>>
get:
description: Get a <<typeName>>
is: [ hasResponseItem: { typeName: <<typeName>> } ]
traits:
hasRequestItem:
body:
application/json:
type: <<typeName>>
hasResponseItem:
responses:
200:
body:
application/json:
type: <<typeName>>
hasResponseCollection:
responses:
200:
body:
application/json:
type: <<typeName>>[]
/myResource:
type: { collection: { typeName: Response } }
get:
/{id}:
type: { item: { typeName: Response } }
post:
body:
application/json:
您可以将id
字段标记为readOnly
以使意图清晰,尽管它不会影响数据的验证方式。
要影响验证,您可以创建"读取"类型和"写入"类型,其中"读取"类型具有额外必需的id
属性。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"MyWriteEntity": {
"type": "object",
"properties": {
"something1": { "type": "string"},
"something2": { "type": "string"}
},
"required": "something1"
},
"MyReadEntity": {
"allOf": [
{ "$ref": "#/definitions/MyWriteEntity" },
{
"id": { "type": "string", "readOnly": true},
"required": ["id"]
}
]
}
}
}
做到这一点的最佳方法是创建一个RAML库片段,请说" foo.raml"。对于数据模型" foo"用于资源/foos和/foos/{fooid}。
在库中,创建三种类型:fooinput:特性:事物1:某物2:fooOutput:类型:fooinput特性:id:整数foopatch:特性:1?:2?:
现在,在一个文件中,您有3种数据类型。将输入版本与PUT/POST一起使用,使用输出版本进行get和使用补丁版作为补丁端点。与ResousceType配对时,这甚至更好。