3

我需要验证我的 aws lambda 事件模式。我用进行验证。我有两个不同的案例。

  1. lambda 函数仅支持一种类型的事件。

像这样

var vandium = require('vandium');

vandium.validation({
    name: vandium.types.string().required()
});

exports.handler = vandium(function (event, context, callback) {
    console.log('hello: ' + event.name);
    callback(null, 'Hello from Lambda');
});

在这种情况下,vandium仅验证 key 是否存在。但我需要检查是否存在任何额外的密钥。

  1. lambda 函数支持多种类型的事件。

像这样

var vandium = require('vandium');

vandium.validation({

    operation: vandium.types.string().required(),
    name: vandium.types.string().required(), });

exports.handler = vandium(function (event, context, callback) {

    const operation = event.operation;
    switch (operation) {
        case 'test1':
            test1(event);
            break;
        case 'test2':
            test2(event);
            break;

        default:
            callback(new Error("Unrecognized operation=" + operation));
            break;
    }


    function test1(event) {
        //console.log('hello: ' + event.name);
        callback(null, 'Hello from Lambda');
    }

    function test2(event) {
        //console.log('hello: ' + event.name);
        callback(null, 'Hello from Lambda');
    }

});

在这种情况下,test1 和 test2 的事件是不同的。像这样

test1{"name":"hello","id":100 }

test2{"schoolName":"threni","teacher":"abcd" }

  1. 对于此类问题,哪个是最好的 scema 验证 npm 包?
  2. vandium适合json 验证吗?
4

2 回答 2

1

对于那些需要在 aws lambda 函数上验证事件的人,@middy/validator 会有所帮助。在此示例中,您需要执行第 1 步:

import validator from '@middy/validator';

step2:定义架构

const schema = {
  properties: {
    body: {
      type: 'object',
      properties: {
        name: {
          type: 'string',
        },
      },
      required: ['name'],
    },
  },
  required: ['body'],
};

step3:使用验证器中间件

export const handler = Your_Lambda_Function
  .use(validator({ inputSchema: schema }));
于 2021-05-24T04:16:39.090 回答
1

你看过ajv吗?就像Validating Data With JSON-Schema

于 2016-09-05T10:40:36.197 回答