2017-08-21 19 views
0

我正在編寫一個lambda函數來通過發佈電話號碼來獲取資源。下面是我的代碼。對使用​​API​​網關爲DynamoDB創建更新請求感到困惑

exports.handle = function (e, ctx, cb) { 
    var body = JSON.parse(e.body); 
    var params = { 
     TableName: 'userAddresses', 
     FilterExpression: '#phone = :phone', 
     ExpressionAttributeNames: { 
      "#phone": "phone" 
     }, 
     ExpressionAttributeValues: { 
      ":phone": body.phone 
     } 
    } 
    dynamodb.scan(params).promise().then(function (data) { 
     var uw = data.Items[0]; 
     var res = { 
      "statusCode": 200, 
      "headers": {}, 
      "body": JSON.stringify(uw) 
     }; 
     ctx.succeed(res); 
    }); 
} 

這工作正常。但我想用put和patch來做同樣的事情。有人可以指點我一個正確的方向。

補丁,它應該是類似的phone應作爲一個queryParameter和身體傳遞在短短的JSON體進行更新

感謝

回答

0

的電話號碼的哈希鍵?如果是這樣,使用dynamodb.get()或dynamodb.query(),而不是...

這裏有一個快速和骯髒的例子,它可以幫助你開始使用DynamoDB更新:

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

AWS.config.setPromisesDependency(bluebird); 

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

let update = (id, attributes) => { 
    var params = { 
    TableName: 'MyTableName', 
    Key: { 
     myHashKeyAttr: id 
    }, 
    AttributeUpdates: attributes 
    }; 

    return dynamodb.update(params).promise(); 
}; 

exports.handler = (event, context, callback) => { 
    console.log(JSON.stringify(event, null, 2)); 
    let body = JSON.parse(event.body); 

    let attributes = { 
    firstName: { 
     Action: 'PUT', 
     Value: body.firstName 
    }, 
    lastName: { 
     Action: 'PUT', 
     Value: body.lastName 
    }, 
    updatedAt: { 
     Action: 'PUT', 
     Value: new Date() 
    } 
    }; 

    // only if the phone number is a hash key... 
    update(event.queryStringParameters.phone, attributes) 
    .then(

     (result) => { 
     console.log(result); 
     callback({ 
      statusCode: 200, 
      headers: {}, 
      body: JSON.stringify({message: 'updated!'}) 
     }); 
     } 

    ).catch(

     (error) => { 
     console.error(error); 
     callback({ 
      statusCode: 500, 
      headers: {}, 
      body: JSON.stringify({message: 'ops!'}) 
     }); 
     } 

    ); 
}