javascript 从DynamoDB响应中删除数据类型描述符的推荐方法是什么?

pkln4tw6  于 2023-09-29  发布在  Java
关注(0)|答案(7)|浏览(102)

DynamoDB为查询响应中的每个元素包含一个数据类型描述符,如下所示:

"Item": { 
    "M" : {
        "Age": {"N": "8"},
        "Name": {"S": "Fido"},
        "Vaccinations": {
            "M": {
                "Rabies": {
                    "L": [
                        {"S": "2009-03-17"},
                        {"S": "2011-09-21"},
                        {"S": "2014-07-08"}
                    ]
                },
                "Distemper": {"S": "2015-10-13"}
            }
        }
    }
}

我想剥离所有这些描述符(“S”,“L”,“M”等),以便它看起来像下一个例子,在I JSON.stringify数据之前。

"Item": {
    "Age": "8",
    "Name": "Fido",
    "Vaccinations": {
        "Rabies": [
            "2009-03-17",
            "2011-09-21",
            "2014-07-08"
         ]
         "Distemper": "2015-10-13"
     }
}

是否有标准(或推荐)方法来执行此操作?

kmbjn2e3

kmbjn2e31#

他们有一个转换器,你可以使用。
例如,以下是他们的示例:

var data= {"Item": {
    "Age": {"N": "8"},
    "Name": {"S": "Fido"},
    "Vaccinations": {
        "M": {
            "Rabies": {
                "L": [
                    {"S": "2009-03-17"},
                    {"S": "2011-09-21"},
                    {"S": "2014-07-08"}
                ]
            },
            "Distemper": {"S": "2015-10-13"}
        }
}}};
var marshalled = AWS.DynamoDB.Converter.unmarshall(data);

https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html

daupos2t

daupos2t3#

不熟悉使用DynamoDb。我猜有一些SDK可以帮你做到这一点,或者可以用来关闭描述符的查询设置
以下似乎适用于您的示例中的所有情况

var descriptors = ['L', 'M', 'N', 'S'];

function flatten(o) {

  // flattens single property objects that have descriptors  
  for (let d of descriptors) {
    if (o.hasOwnProperty(d)) {
      return o[d];
    }
  }

  Object.keys(o).forEach((k) => {

    for (let d of descriptors) {
      if (o[k].hasOwnProperty(d)) {
        o[k] = o[k][d];
      }
    }
    if (Array.isArray(o[k])) {
      o[k] = o[k].map(e => flatten(e))
    } else if (typeof o[k] === 'object') {
      o[k] = flatten(o[k])
    }
  });

  return o;
}

data = flatten(data)
console.log(data)
.as-console-wrapper {
  max-height: 100%;
}
<script>
  var data = {"Item":{"Age":{"N":"8"},"Name":{"S":"Fido"},"Vaccinations":{"M":{"Rabies":{"L":[{"S":"2009-03-17"},{"S":"2011-09-21"},{"S":"2014-07-08"}]},"Distemper":{"S":"2015-10-13"}}}}};
</script>
kyxcudwk

kyxcudwk4#

也许像这样:

var data= {"Item": {
    "Age": {"N": "8"},
    "Name": {"S": "Fido"},
    "Vaccinations": {
        "M": {
            "Rabies": {
                "L": [
                    {"S": "2009-03-17"},
                    {"S": "2011-09-21"},
                    {"S": "2014-07-08"}
                ]
            },
            "Distemper": {"S": "2015-10-13"}
        }
}}};

var keys_black_list=['N', 'S', 'M', 'L'];

function correct_data(_data){
  var new_data={};
  for(var key in _data){
	   if (typeof _data[key] === 'object') {
	   	   for(var bl_key in keys_black_list){
	   	   	  if(_data[key][keys_black_list[bl_key]]){

	   	   	  	 if(typeof _data[key][keys_black_list[bl_key]] === 'object'){
	   	   	  	 	new_data[key]=correct_data(_data[key][keys_black_list[bl_key]]);
	   	   	  	 }else{
	   	   	  	 	new_data[key]=_data[key][keys_black_list[bl_key]];
	   	   	  	 }
	   	   	  }
	   	   }
	   }
  }
  return new_data;
}


console.log(correct_data(data.Item));
f0brbegy

f0brbegy5#

在sdkversion3中,有一个马歇尔和unmarshall实用程序
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_util_dynamodb.html

import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';

try {
  const data = await ddbClient.send(new GetItemCommand(configReadService.params));
  return unmarshall(data.Item) as unknown as ConfigAssets;
} catch (e) {
  console.log('Reading the configuration database failed ', e)
}
13z8s7eq

13z8s7eq6#

在发送最终响应之前调用此函数。

function parseDynamoDBItem(
item: Record<string, DynamoDBItem>
): Record<string, any> {
 const result: Record<string, any> = {};
for (const key of Object.keys(item)) {
const value = item[key];
if (value.S) {
  result[key] = value.S;
} else if (value.N) {
  result[key] = Number(value.N);
} else if (value.L) {
  result[key] = value.L.map((item: any) => parseDynamoDBItem(item));
} else if (value.M) {
  result[key] = parseDynamoDBItem(value.M);
}
}
return result;
}

调用上述函数。

const bookmarks = await getBookmarkDetailsForUser(userId);

  const bookmarksWithoutDataTypes = bookmarks.map((bookmark) =>
    parseDynamoDBItem(bookmark)
  );
  const response = JSON.stringify(bookmarksWithoutDataTypes);

  return {
    statusCode: 200,
    body: response,
  };
3z6pesqy

3z6pesqy7#

通过使用DynamoDB DocumentClient,正如@bwinant所建议的那样,可以完全避免类型描述符。
下面的示例在http请求处理程序中使用docClient get()和put():

// handleHttpRequest is the entry point for Lambda requests
exports.handleHttpRequest = function(request, context, done) {
  try {
    const id = request.pathParameters.id;
    let response = {
      headers: {},
      body: '',
      statusCode: 200
    };

    switch (request.httpMethod) {
      case 'GET': {
        let dynamo = new AWS.DynamoDB();
        var params = {
          TableName: myTable,
          Key: { 'id' : id },
        };

        docClient.get(params, function(err, data) {
          if (err) {
            throw `Dynamo Get Error (${err})`
          } else {
            response.body = JSON.stringify(data.Item);
            done(null, response);          
          }
        });
        break;
      }

      case 'POST': {
        let myData = JSON.parse(request.body || '{}');
        let params = {
          TableName: myTable,
          Item: {
            id : id,
            my_data : myData
          }
        }
        docClient.put(params, function(err, data) {
          if (err) {
            throw `Dynamo Put Error (${err})`;
          } else {
            done(null, data);
          }
        });
      }
    }
  } catch (e) {
    done(e, null);
  }
}

相关问题