【问题标题】:In a serverless.yml file, how does one customize the default http response template?在 serverless.yml 文件中,如何自定义默认的 http 响应模板?
【发布时间】:2020-02-14 09:51:49
【问题描述】:

查看https://serverless.com/framework/docs/providers/aws/events/apigateway/#custom-response-templates 此处的文档,似乎没有太多关于设置这些模板的详细信息。

我目前正在寻找删除默认的application/json 内容类型,它是在创建处理程序的集成响应期间生成的(如下图所示),并将其替换为text/html。是否有定义的语法来隐藏某处?或者这种级别的定制在当前框架范围内是不可能的?

这是我在 serverless.yml 中定义的端点

events:
      - http:
          method: any
          path: /
          integration: lambda
          request:
            region: ${env:AwsRegion}
          response:
            headers:
              Content-Type: "'text/html'"
            template: $input.path('body')
       - http:
          method: any
          path: /{proxy+}

在 AWS Api Gateway 上产生以下配置:

作为猜测,我确实尝试过像这样修改规范,但它引发了语法错误:

template: 
  text\html: $input.path('body')

【问题讨论】:

  • 我认为对于响应模板,您只需将其放入 template 中即可。 template: $input.path('body')。响应的类型由Content-Type 处理。对于请求模板,您可以根据内容类型使用不同的模板,在这种情况下,您可以按照自己的尝试进行操作。

标签: aws-lambda aws-api-gateway serverless-framework


【解决方案1】:

让它工作

框架似乎并不真正支持这一点,但可以通过 (ab) 在无服务器模板中使用 statusCodes 将其破解。

将响应模板移动到状态代码下,并为该状态代码提供pattern,完成我认为您所追求的。语法:

      - http:
          method: any
          path: /
          integration: lambda
          request:
            region: us-east-1
          response:
            headers:
              Content-Type: "'text/html'"
            statusCodes:
              200:
                pattern: ""
                template:
                  text/html: $input.path('body')

注意:patterntemplate 都必须存在。


真的那么糟糕吗?

这最终取决于你。我称其为 hack 是因为:

  • 如果能够在response.template 级别而不是response.statusCodes.200.template 级别提供此功能会更好。
  • 指定一个或多个 statusCodes 会删除您在未指定任何内容时获得的一组默认 lambda 错误正则表达式。
  • 感觉就像解决response.template 只接受字符串,而它可以(应该?)接受字符串或对象(就像在statusCodes 下一样)这一事实。

修复它?

offending code,来自/lib/plugins/aws/package/compile/events/apiGateway/lib/method/integration.js

        if (http.response.template) {
          _.merge(integrationResponse.ResponseTemplates, {
            'application/json': http.response.template,
          });
        }

        if (config.template) {
          const template =
            typeof config.template === 'string'
              ? { 'application/json': config.template }
              : config.template;

          _.merge(integrationResponse.ResponseTemplates, template);
        }

我认为要在response.template 下工作,第一个if() 中的代码需要表现得更像第二个if() 中的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多