node.js - Lambda 始终返回 200

标签 node.js aws-lambda amazon-dynamodb

当我为 Lambda 函数提供 GetItem 调用的无效主键时,它似乎会搜索该键直到超时,但它仍然只返回 200(没有响应正文)。

是否有任何方法可以确保函数在遍历完表一次之后就中止,而没有找到 key 并返回错误消息?一遍又一遍地查看直到超时似乎是浪费函数时间?此外,它在 1000 毫秒后超时,这不是我的函数超时设置,这让我认为这里除了常规超时之外还发生了其他事情。

代码:

'use strict';

const AWS = require('aws-sdk');

const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {

  const done = (err, res) => {

    const response = {
      statusCode: err ? '400' : '200',
      body: err ? JSON.stringify(err) : JSON.stringify(res)
    }

    callback(null, response);

  };

  const groupId = event.pathParameters.groupId;
  const eventId = event.pathParameters.eventId;

  docClient.get({
      TableName: 'events',
      Key: {
        groupId,
        eventId
      }
   },
    (err, data) => {
      done(err, data.Item);
    });
};

最佳答案

In a perfect world, I would like for the function to stop once it has "realized" that I have supplied an incorrect primary key and then return some error that would tell the client that it could not find an item in the table with that primary key, yes!

只有当我们让数据库操作来完成这件事时,才会发生这种情况!所以我们必须依赖数据库的响应。

这是我们可以做的:基于响应返回错误,无论是 200 还是 400!

使用您的 done 函数检查 Lodash 的 res isEmpty 方法是否返回 400。

'use strict';

const AWS = require('aws-sdk');

const docClient = new AWS.DynamoDB.DocumentClient();

const { isEmpty }  = require('lodash');

exports.handler = (event, context, callback) => {

  const done = (err, res) => {

    const response = {
      statusCode: (err || isEmpty(res)) ? '400' : '200',
      body: err ? JSON.stringify(err) : JSON.stringify(res)
    }

    callback(null, response);

  };

  const groupId = event.pathParameters.groupId;
  const eventId = event.pathParameters.eventId;

  docClient.get({
      TableName: 'events',
      Key: {
        groupId,
        eventId
      }
   },
    (err, data) => {
      done(err, data.Item);
    });
};

希望这能解决您的疑问!

关于node.js - Lambda 始终返回 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579407/

相关文章:

node.js - Passenger、Plesk 和 Node.js : address already in use

node.js - Backbone : TypeError: Cannot call method 'apply' of undefined

mysql - 什么ip AWS lambda函数使用?

amazon-web-services - aws-sdk : DynamoDB : Fetch list of all tables

ios - DynamoDB iOS : AWSDynamoDBScanExpression Provide multiple parameters for scanFilter property

node.js - ansible 安装 node.js 版本 6

node.js - 哪些 NodeJS 框架支持关系数据库?

python - 通过 AWS Lambda 在 AWS Redshift 中插入数据

Python - 创建 aws lambda 部署包

amazon-web-services - "Real-Time"DynamoDB 流怎么样?