Ser*_*hap 18 amazon-web-services aws-api-gateway serverless-framework serverless-plugins
我想定义请求和响应模型.我在AWS中使用无服务器框架,我所看到的一切建议使用无服务器aws文档
README说我需要有这条线 custom.documentation.models.MODELNAME
schema: ${file(models/error.json)}
Run Code Online (Sandbox Code Playgroud)
但是他们没有models/error.json用作基线的示例文件.
在实际的例子中,serverless.yml有一个这样的定义:
-
name: DoSomethingRequest
contentType: "application/json"
schema:
type: array
items:
type: string
Run Code Online (Sandbox Code Playgroud)
这没有为我正在尝试做的事情提供足够的细节.
我的目标是为字符串对象,消息和状态代码数组定义模式.但是,消息和状态代码是可选的.这些也可能是其他模型的一部分,如果可能的话,我不想重复每个模型的定义.
我目前的尝试是:
-
name: ReturnArrayResponse
contentType: "application/json"
schema:
type: array
itemsArray:
type: string
message:
type: string
statusCode:
type: number
Run Code Online (Sandbox Code Playgroud)
我认为这会做我想要的,但我怎么能拥有message并可statusCode选择并在我的其他模特中重复这两个项目?
我很满意我可以放入我的serverless.yml文件或我可以引用的json文件的yml解决方案.
包括一个文件
在给出的示例中,error.json可以包含任何有效的架构。如此简单的事情就可以了:
{"type":"object","properties":{"message":{"type":"string"}}}
也可以包含诸如$schema和的属性title:
{
"$schema" : "http://json-schema.org/draft-04/schema#",
"title" : "Error Schema",
"type" : "object",
"properties" : {
"message" : { "type" : "string" },
"statusCode": { "type": "number" },
"itemsArray": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当您已经在AWS中定义了模型但没有无服务器Yaml来构建它们时,这特别方便。您可以简单地从AWS控制台中复制架构,将json粘贴到文件中,然后使用schema: ${file()}问题中提到的语法。据我所知,您可以使AWS控制台接受。
干
我不知道从无服务器文件中的其他模型中引用模型的方法,但是您可以使用与插件作者相同的方法,只需将需要重用的所有内容放在之外,models并在更易于重用的位置使用即可。插件作者使用commonModelSchemaFragments。
因此,如果您有一些像这样的片段:
commonModelSchemaFragments:
# defining common fragments means you can reference them with a single line
StringArrayFragment:
type: array
items:
type: string
HttpResponse:
type: object
properties:
message:
type: string
statusCode:
type: number
Run Code Online (Sandbox Code Playgroud)
您可以在模型中引用这些片段:
-
name: HttpStatusResponse
contentType: "application/json"
schema:
type: object
properties:
serverResponse:
${self:custom.commonModelSchemaFragments.HttpResponse}
messageArray:
${self:custom.commonModelSchemaFragments.StringArrayFragment}
Run Code Online (Sandbox Code Playgroud)
标记属性可选
您可以通过将属性标记为来完成此操作required。只需提供所有属性的列表即可,但您想要成为可选属性的除外。的JSON模式如下所示:
{
"type": "object",
"required": ["message"],
"properties": {
"optionalMessage": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过在无服务器文件中使用yaml来构建该文件:
-
name: OptionalResponse
contentType: "application/json"
schema:
type: object
required:
- "message"
properties:
message:
type: string
optionalMessage:
type: string
Run Code Online (Sandbox Code Playgroud)
关于请求验证的注意事项
标记属性required或optional仅在打开请求正文验证时才重要:
我不知道使用任何特殊的无服务器语法打开请求验证的方法。看起来您可以在本resources节中做到这一点,但我还没有尝试过。 来源。
| 归档时间: |
|
| 查看次数: |
1742 次 |
| 最近记录: |