Last active
April 9, 2020 18:55
-
-
Save dtelaroli/5863acb8e440d5a739fa8633e91c0612 to your computer and use it in GitHub Desktop.
Lambda to update all DynamoDB data to force reindex ElasticSearch AppSync Amplify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { DynamoDB } = require("aws-sdk"); | |
const ddb = new DynamoDB.DocumentClient(); | |
/** | |
* @param event.TableName required - DynamoDB table name | |
* @param event.ExclusiveStartKey optional - Last Id if you want continue previeus execution | |
* Permissions to lambda: | |
* - dynamodb:Scan | |
* - dynamodb:BatchWriteItem | |
**/ | |
exports.lambdaHandler = async (event, context) => { | |
console.log(event); | |
return await update(event.TableName, event.ExclusiveStartKey); | |
}; | |
const update = async (TableName, ExclusiveStartKey) => { | |
try { | |
while (true) { | |
const params = { | |
TableName, | |
ExclusiveStartKey, | |
Limit: 25 | |
}; | |
const data = await ddb.scan(params).promise(); | |
ExclusiveStartKey = data.LastEvaluatedKey; | |
const saved = await updatePage(TableName, data.Items); | |
console.log(saved, ExclusiveStartKey); | |
if (!ExclusiveStartKey) { | |
return "Ok"; | |
} | |
} | |
} catch (error) { | |
console.log(error); | |
return "Error"; | |
} | |
}; | |
const updatePage = async (TableName, items) => { | |
const updatedAt = new Date().toISOString(); | |
const params = { | |
RequestItems: {} | |
}; | |
params.RequestItems[TableName] = items.map(Item => { | |
return { | |
PutRequest: { | |
Item: { ...Item, updatedAt } | |
} | |
}; | |
}); | |
return ddb.batchWrite(params).promise(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment