【问题标题】:AWS Lambda NodeJS writing to S3 behaves differently on local and severAWS Lambda Node JS 写入 S3 在本地和服务器上的行为不同
【发布时间】:2020-10-12 06:21:57
【问题描述】:

我使用无服务器创建了一个 NodeJS Lambda 函数。它从 DynamoDB 表中读取数据并将数据写入 S3 存储桶。

这是我的handler.js:(显示受影响的功能):

module.exports.exportContactsByClientID = (event, context, callback) => {
  // const id = event.pathParameters.id.toLowerCase();
  const id= 'mkh';
  
  const params = {
    TableName: contactsTable,
    IndexName: "client_code-created_at_local-index",
    KeyConditionExpression: "client_code = :v_ID",
    ExpressionAttributeValues: {
      ":v_ID": id,
    },
    ProjectionExpression: "client_code, created_at, contact_name, age, phone, email, dsr_ratio, max_eligibility, selected_banks"
  };

return db.query(params)
.promise()
.then((res) => {
  // console.log(res);
  const items = res.Items;
  // Headers + Columns
  worksheet.cell(1, 1).string('Client').style({font: {bold: true}});
  worksheet.cell(1, 2).string('Name').style({font: {bold: true}});
  worksheet.cell(1, 3).string('Age').style({font: {bold: true}});
  worksheet.cell(1, 4).string('Email').style({font: {bold: true}});
  worksheet.cell(1, 5).string('Phone').style({font: {bold: true}});
  worksheet.cell(1, 6).string('DSR Ratio').style({font: {bold: true}});
  worksheet.cell(1, 7).string('Max Eligibility').style({font: {bold: true}});
  // Rows
  // items.sort((a, b) => (a.date > b.date) ? -1 : 1);
  items.forEach((item, i) => {
    console.log(item.contact_name);
    worksheet.cell(i + 2, 1).string(item.client_code);
    worksheet.cell(i + 2, 2).string(item.contact_name);
    worksheet.cell(i + 2, 3).string(item.age);
    worksheet.cell(i + 2, 4).string(item.email);
    worksheet.cell(i + 2, 5).string(item.phone);
    worksheet.cell(i + 2, 6).string(item.dsr_ratio);
    worksheet.cell(i + 2, 7).string(item.max_eligibility);
  });
  console.log(contactsBucket);
  console.log(id);
  workbook.writeToBuffer().then(buffer => {
    console.log('inside writetoubgger')
    var params = {
      Bucket: contactsBucket,
      Key: `contacts/mkh.xlsx`,
      Body: buffer,
      ACL: 'public-read'
    }
    S3.upload(params, function(err, data) {
      if (err) {
        console.log(err, err.stack);
      } else {
        // callback(null, response(200, res));
        callback(null, response(200, res));
      }
    });
  })
})
.catch((err) => callback(null, response(err.statusCode, err)));
};

我的serverless.yml

service: mhub-dsr-calculator-api

plugins:
  - serverless-plugin-include-dependencies

package:
  exclude:
    - node_modules/**

custom:
  allowed-headers:
      - Content-Type
      - Authorization
      - X-Api-Token
      - X-Origin
      - X-Amz-Date
      - X-Amz-Security-Token
  settings:
    CONTACTS_TABLE: dsrcalculator-contacts-dev
    CONTACTS_BUCKET: mhub-dsrcalculator-contacts

provider:
  name: aws
  runtime: nodejs12.x
  environment: ${self:custom.settings}
  region: ap-southeast-1 
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
        - dynamodb:Query
      Resource:
        - "arn:aws:dynamodb:${self:provider.region}:*:table/${self:custom.settings.CONTACTS_TABLE}"
    - Effect: "Allow"
      Action:
        - dynamodb:Query
      Resource:
        - "arn:aws:dynamodb:${self:provider.region}:*:table/${self:custom.settings.CONTACTS_TABLE}/index/client_code-created_at_local-index"
    - Effect: "Allow"
      Action:
       - "s3:*"
      Resource: 
       - "arn:aws:s3:::${self:custom.settings.CONTACTS_BUCKET}/*"

functions:
  createPost:
    handler: handler.createContact
    events:
    - http:
        path: /contact
        method: post
        cors: true
  updatePost:
    handler: handler.updateContact
    events:
    - http:
        path: /contact/{id}
        method: put
        cors: true
  getAllPosts:
    handler: handler.getAllContacts
    events:
    - http:
        path: /contacts
        method: get
        cors: true
  getContactsByClientID:
    handler: handler.getContactsByClientID
    events:
    - http:
        path: /contacts/{id}
        method: get
        cors: true
  exportContactsByClientID:
    handler: handler.exportContactsByClientID
    events:
    - http:
        path: /export/{id}
        method: get
        cors: true

resources:
  Resources:
    PostsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        AttributeDefinitions:
        - AttributeName: "id"
          AttributeType: "S"
        - AttributeName: "client_code"
          AttributeType: "S"
        - AttributeName: "created_at_local"
          AttributeType: "S"
        KeySchema:
        - AttributeName: "id"
          KeyType: "HASH"
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:custom.settings.CONTACTS_TABLE}
        

当我在本地调用函数时(使用serverless invoke local -f exportContactsByClientID)得到以下输出,其中“mhub-dsrcalculator-contacts”是存储桶名称,“mkh”是 id,“inside writetoubgger”表示@987654326 中的代码@跑了。

mhub-dsrcalculator-contacts
mkh
inside writetoubgger

S3 存储桶上的文件创建成功。

但是,当我部署它并进行测试时,尽管它连续运行,但代码并未进入“workbook.writeToBuffer”,如下所示。

2020-06-22T11:23:22.945Z    1ce59a7b-98e4-4c9e-8736-ec7c162c4759    INFO    mhub-dsrcalculator-contacts
2020-06-22T11:23:22.945Z    1ce59a7b-98e4-4c9e-8736-ec7c162c4759    INFO    mkh
END RequestId: 1ce59a7b-98e4-4c9e-8736-ec7c162c4759

为什么会这样?任何指导将不胜感激。谢谢。

【问题讨论】:

    标签: node.js amazon-web-services aws-lambda amazon-dynamodb


    【解决方案1】:

    您的外部承诺正在完成而无需等待writeToBuffer 承诺。

    尝试改变:

    workbook.writeToBuffer().then(...
    

    收件人:

    return workbook.writeToBuffer().then(...
    

    您应该对 S3 上传调用执行相同的操作:

    return S3.upload(params).promise().then(data => {
            callback(null, response(200, res));
    });
    

    我还建议您使用 async / await 语法重写您的代码,这样更易​​于阅读和理解。

    【讨论】:

    • 请问 - 现在从 AWS 调用它时它可以工作,但是当我在浏览器或 Postman 上尝试它时它失败并显示“无法读取未定义的属性 'id'”。
    • 在 AWS 上,我的测试事件被定义为:{ "pathParameters": { "id": "ijm" } } 我没有在我的代码中使用 const id = event.pathParameters.id 正确指定它.toLowerCase(); ?
    • 你应该检查一个空的event.pathParameters
    • console.log(event) 应该可以帮助您调试此问题。
    • 我用 async/await 重写了代码,如下所示:stackoverflow.com/questions/62568043/…(答案)。如果可以或可以进一步改进,感谢您的反馈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2023-03-11
    • 2017-10-07
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    相关资源
    最近更新 更多