无服务器框架 Lamba 集成 - 请求模式验证

Serverless Framework Lamba Integration - Request Schema Validation

我已经查看了在 SO 上可以找到的几个答案,但我仍然没有任何运气。我正在使用无服务器并尝试使用 api 网关 lambda 集成对 lambda 函数的请求主体进行验证。在 运行 sls offline 之后,使用 postman 发出 POST 请求,无论 body 是什么,请求都会成功。验证似乎根本没有发生。

这是我的...

serverless.yml:

service: onboard

# plugins
plugins:
  - serverless-offline

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: us-east-1

functions:
  onboard:
    handler: api/onboard.onboard
    events:
      - http:
          path: onboard
          method: post
          integration: lambda
          request:
            passThrough: NEVER
            schema:
              application/json: ${file(models/onboard.schema.json)}
            template:
              application/json: '{ "body" : "$input.body" }'

api/onboard.js

const onboard = async (event) => {
  const response = {
    message: event
  };

  return response;
};

exports.onboard = onboard;

models/onboard.schema.json:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "https://path.to/onboard",
  "title": "title",
  "description": "description",
  "type": "object",
  "properties": {
    "environment": { "type": "string" },
    "git": { 
      "type": "object",
      "properties": {
        "repo": {
          "type": "string",
          "format": "uri",
          "pattern": ".git$"
        },
        "token": { "type": "string" }
      },
      "required": ["repo", "token"],
      "maxProperties": 2
    },
    "name": {  "type": "string" },
    "team": {
      "type": "string",
      "pattern": "(?i)(^red$|^blue$|^green$|^yellow$|^black$|^white$)"
    }
  },
  "additionalProperties": false,
  "required": ["name", "team"]
}

这里有几点需要注意:

  1. 您的测试请求必须通过符合您配置的Content-Type,否则验证将被忽略。据我所知,强制使用 Content-Type 的唯一方法是将最小验证添加到您的 Lambda 函数中。
  2. serverless-offline 可能不会考虑请求验证。最好在云端测试。就个人而言,我避免在本地进行这些类型的测试,并尝试尽可能多地在云中进行测试。随着无服务器框架发布名为 Studio 的新功能,它通过提供快速周转时间来进行更改、在几秒钟内推送到云并为您提供类似邮递员的界面来将测试发送到您的基础架构,从而使这变得更加容易。云使测试变得更加容易。

Serverless-offline 不支持请求验证 https://github.com/dherault/serverless-offline/issues/369

最好通过定义模拟响应在 apigateway 上单独测试它。这将确保 lambda 响应(如果基于集成类型不正确)不会造成任何误导。