在serverless.yml文件中,如何自定义默认的http响应模板?

In a serverless.yml file, how does one customize the default http response template?

查看此处 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 网关上生成以下配置:

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

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

让它发挥作用

看起来框架并没有真正支持它,但可以通过在无服务器模板中(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 下所做的那样)。
  • =50=]

修复它?

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() 中的代码。