Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. const AWS = require('aws-sdk');
  2.  
  3. const dynamoDbDocumentClient = new AWS.DynamoDB.DocumentClient({
  4. apiVersion: '2012-10-08',
  5. region: 'eu-west-1',
  6. });
  7.  
  8. const openDbConnection = () => dynamoDbDocumentClient;
  9.  
  10. const getTableName = (table) => {
  11. const environment = process.argv[2];
  12. return `${table}${environment}`;
  13. };
  14.  
  15. const scan = async ({
  16. dbConnection, filter, values, table,
  17. }) => {
  18. const { Items } = await dbConnection.scan({
  19. FilterExpression: filter,
  20. ExpressionAttributeValues: values,
  21. TableName: table,
  22. }).promise();
  23. return Items;
  24. };
  25.  
  26. const updateItem = async ({
  27. dbConnection,
  28. table,
  29. id,
  30. expression,
  31. values,
  32. names,
  33. condition,
  34. returnUpdated = false,
  35. }) => {
  36. try {
  37. const result = await dbConnection
  38. .update({
  39. TableName: table,
  40. Key: { id },
  41. UpdateExpression: expression,
  42. ExpressionAttributeValues: values,
  43. ExpressionAttributeNames: names,
  44. ConditionExpression: condition,
  45. ReturnValues: returnUpdated ? 'ALL_NEW' : 'NONE',
  46. })
  47. .promise();
  48. return (returnUpdated && result.Attributes) || true;
  49. } catch (error) {
  50. if (error.code === 'ConditionalCheckFailedException') {
  51. log(`Item ${id} in ${table} did not pass the update condition: ${condition}`);
  52. return false;
  53. }
  54. throw error;
  55. }
  56. };
  57.  
  58. const handler = async () => {
  59. const dbConnection = openDbConnection();
  60. const conversations = await scan({
  61. dbConnection,
  62. table: getTableName('Conversations'),
  63. });
  64.  
  65. const updatedConversations = await Promise.all(
  66. conversations.map(async (conversation) => updateItem({
  67. dbConnection,
  68. table: getTableName('Conversations'),
  69. id: conversation.id,
  70. expression: 'SET groupDetails = :groupDetails',
  71. values: { ':groupDetails': null },
  72. condition: 'attribute_not_exists(groupDetails)',
  73. returnUpdated: true,
  74. })),
  75. );
  76.  
  77. console.log(updatedConversations);
  78. };
  79.  
  80. handler();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement