|
| 1 | +// Adding a new field "hasWikiPage" |
| 2 | +// "hasWikiPage" is a boolean field that is set to true if the item has a wiki page |
| 3 | +// It is calculated with a prepare function that fetches the wiki page status for each item |
| 4 | + |
| 5 | +const { utils } = require('dynamo-data-transform'); |
| 6 | + |
| 7 | +const userAgentHeader = { |
| 8 | + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36', |
| 9 | +}; |
| 10 | + |
| 11 | +const fetch = (...args) => import('node-fetch').then(({ default: nodeFetch }) => nodeFetch( |
| 12 | + ...args, |
| 13 | + { |
| 14 | + headers: userAgentHeader, |
| 15 | + }, |
| 16 | +)); |
| 17 | + |
| 18 | +const TABLE_NAME = 'UsersExample'; |
| 19 | + |
| 20 | +const transformUp = async ({ ddb, preparationData, isDryRun }) => { |
| 21 | + const addHasWikiPage = (hasWikiDict) => (item) => { |
| 22 | + const valueFromPreparation = hasWikiDict[`${item.PK}-${item.SK}`]; |
| 23 | + const updatedItem = valueFromPreparation ? { |
| 24 | + ...item, |
| 25 | + hasWikiPage: valueFromPreparation, |
| 26 | + } : item; |
| 27 | + return updatedItem; |
| 28 | + }; |
| 29 | + |
| 30 | + return utils.transformItems( |
| 31 | + ddb, |
| 32 | + TABLE_NAME, |
| 33 | + addHasWikiPage(JSON.parse(preparationData)), |
| 34 | + isDryRun, |
| 35 | + ); |
| 36 | +}; |
| 37 | + |
| 38 | +const transformDown = async ({ ddb, isDryRun }) => { |
| 39 | + const removeHasWikiPage = (item) => { |
| 40 | + const { hasWikiPage, ...oldItem } = item; |
| 41 | + return oldItem; |
| 42 | + }; |
| 43 | + |
| 44 | + return utils.transformItems(ddb, TABLE_NAME, removeHasWikiPage, isDryRun); |
| 45 | +}; |
| 46 | + |
| 47 | +const prepare = async ({ ddb }) => { |
| 48 | + let lastEvalKey; |
| 49 | + let preparationData = {}; |
| 50 | + |
| 51 | + let scannedAllItems = false; |
| 52 | + |
| 53 | + while (!scannedAllItems) { |
| 54 | + const { Items, LastEvaluatedKey } = await utils.getItems(ddb, lastEvalKey, TABLE_NAME); |
| 55 | + lastEvalKey = LastEvaluatedKey; |
| 56 | + |
| 57 | + const currentPreparationData = await Promise.all(Items.map(async (item) => { |
| 58 | + const wikiItemUrl = `https://en.wikipedia.org/wiki/${item.name}`; |
| 59 | + const currWikiResponse = await fetch(wikiItemUrl); |
| 60 | + return { |
| 61 | + [`${item.PK}-${item.SK}`]: currWikiResponse.status === 200, |
| 62 | + }; |
| 63 | + })); |
| 64 | + |
| 65 | + preparationData = { |
| 66 | + ...preparationData, |
| 67 | + ...currentPreparationData.reduce((acc, item) => ({ ...acc, ...item }), {}), |
| 68 | + }; |
| 69 | + |
| 70 | + scannedAllItems = !lastEvalKey; |
| 71 | + } |
| 72 | + |
| 73 | + return preparationData; |
| 74 | +}; |
| 75 | + |
| 76 | +module.exports = { |
| 77 | + transformUp, |
| 78 | + transformDown, |
| 79 | + prepare, |
| 80 | + transformationNumber: 4, |
| 81 | +}; |
0 commit comments