DynamoDB.putItem函数未使用sls命令保存项目

时间:2018-11-18 13:14:11

标签: node.js aws-lambda amazon-dynamodb serverless-framework

我在使用无服务器框架的Lambda函数时遇到了麻烦,该框架应该将数据放入DynamoDB。我不确定这个问题,因为在运行sls invoke local -f scrape -d 'the-last-bookstore-los-angeles时控制台中没有错误消息。

saveRatingsToDB.js

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

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

module.exports = (data, businessName) => {
  console.log('data saving...');
  console.log(data);
  const params = {
    TableName: process.env.DYNAMODB_TABLE,
    Item: {
      id: uuid.v1(),
      businessName: businessName,
      reviewCount: data.reviewCount,
      rating: data.rating,
      createdAt: JSON.stringify(new Date())
    }
  };

  // I am can log params okay, but nothing with dynamoDb.put is logged to the console

  dynamoDb.put(params, error => {
    console.log('putting data');
    if (error) {
      console.log(`Error saving data to DynamoDB: ${JSON.stringify(error)}`);
      return Promise.reject(
        `Error saving data to DynamoDB: ${JSON.stringify(error)}`
      );
    } else {
      console.log('data saved');
      return Promise.resolve(params.Item);
    }
  });
};

handler.js

'use strict';
const { getPage, parsePage, saveRatingsToDB } = require('./utils');

module.exports.scrape = async (event, context) => {
  console.log('Function triggered', event);
  const name = event;
  const page = await getPage(name);
  const data = await parsePage(page);
  const db = await saveRatingsToDB(data, name);

  return db;
};

serverless.yaml

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: eu-west-2
  environment:
    DYNAMODB_TABLE: my-table-name
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn_reference_"
package:
  include:
    - utils/**

如上所述,控制台中没有错误消息。我可以登录并从params看到saveRatingsToDB.js对象,但实际dynamoDb.put函数中什么都没有。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您尝试通过以下方式将saveRatingsToDB作为异步函数运行:

const db = await saveRatingsToDB(data, name);

不幸的是,按照当前编写此函数的方式,它不是异步函数。在dynamoDb.put中看不到日志的原因是因为saveRatingsToDB函数不等待异步回调完成而是更早返回。

要使saveRatingsToDB正确地成为异步函数并强制其等待回调,您可以返回dynamoDb.put作为该函数的承诺:

module.exports = (data, businessName) => {
  ...

  // use dynamoDb.put().promise() to return a promise from dynamoDb transaction
  return dynamoDb.put(params, error => {
    ...
    // Do whatever with the error
  }).promise();
};