所以我要从我的RAML规范中提取一个JSON模式,以验证GET方法中的输出以及POST方法中的输入。
每个这种类型的实体都有一个“必需的” ID属性-至少在“获取项目”或“获取集合”请求中列出这些实体时是必需的。 但是,当验证接收到的帖子数据以创建这样的实体时,显然不需要ID(并且无论如何都要将其丢弃)。
使GET请求需要此ID属性而不是POST请求的类型中最好不存在该ID属性的最佳DRY方法是什么?
TL; DR:从下面开始阅读;)
易于理解的示例
对于GET请求,类型应为:
properties:
id:
something1:
something2?:
对于POST请求,类型应为:
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>>
在此组合中不起作用。
答案 0 :(得分:1)
您可以将id
字段标记为documentation以使意图清晰,尽管这不会影响数据验证的方式。
要影响验证,可以创建“读取”类型和“写入”类型,其中“读取”类型具有额外的必需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"]
}
]
}
}
}
答案 1 :(得分:1)
我想不出没有两种类型的方法。但是此示例至少只能使您仅传递一种类型,并自动为POST请求在类型名称后附加“ 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: